Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading