Home > Software engineering >  Assign value in dataframe from list by list's element name = dataframe row number
Assign value in dataframe from list by list's element name = dataframe row number

Time:11-24

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.

CodePudding user response:

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
  • Related