Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value in dataframe from list by list's element name = dataframe row number

I have a name list, such as the following:

> myNamedList

(...)

$`1870`
[1] 84.24639

$`1871`
[1] 84.59707

(...)

I would like to assign these values in a dataframe's column where the list element's name corresponds to the dataframe's row number. For now I am proceeding like this:

for (element in names(myNamedList)) {
  targetDataFrame[as.numeric(element),][[columnName]] = myNamedList[[element]]
}

This is quite slow if the list is somewhat large, and also not very R-esque. I believe I could do something with apply, but am not sure where to look. Appreciate your help.

like image 873
M2FKXY Avatar asked Oct 29 '25 09:10

M2FKXY


1 Answers

Add a row number to original data, then stack the list, then merge. See example:

# example
#data
set.seed(1); d <- data.frame(x = sample(LETTERS, 5))
#named list
x <- list("2" = 11, "4" = 22)

#add a row number
d$rowID = seq(nrow(d))

# stack the list, and merge
merge(d, stack(x), by.x = "rowID", by.y = "ind", all.x = TRUE)
#   rowID x values
# 1     1 Y     NA
# 2     2 D     11
# 3     3 G     NA
# 4     4 A     22
# 5     5 B     NA
like image 156
zx8754 Avatar answered Nov 01 '25 00:11

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!