I have a list object where the values in each element are row numbers and the name of each element is an id. Something like this:
> (lst <- list("1" = c(4, 6), "2" = c(3, 5, 7), "3" = c(1,2)))
$`1`
[1] 4 6
$`2`
[1] 3 5 7
$`3`
[1] 1 2
I have a data frame that looks something like this:
> (d <- data.frame(x = round(rnorm(7), 2), id = NA))
x id
1 -1.22 NA
2 1.10 NA
3 -0.42 NA
4 0.97 NA
5 0.31 NA
6 -1.84 NA
7 -0.07 NA
I would like to take the names of the list object elements and insert into the data frame using the list object values as row numbers. The result should look like this:
x id
1 -1.22 3
2 1.10 3
3 -0.42 2
4 0.97 1
5 0.31 2
6 -1.84 1
7 -0.07 2
I thought this code would work:
d$id[unlist(lst)] <- names(unlist(lst))
But that results in this:
x id
1 -1.22 31
2 1.10 32
3 -0.42 21
4 0.97 11
5 0.31 22
6 -1.84 12
7 -0.07 23
Apparently unlist() appends values to names. I know I could take the additional step to remove the added value after the fact using sub(), but I was wondering if there’s a more efficient way to accomplish this.
>Solution :
> d$id[unlist(lst)] <- rep(names(lst), lengths(lst))
> d
x id
1 2.16 3
2 1.74 3
3 1.16 2
4 -1.76 1
5 0.56 2
6 -0.41 1
7 -0.27 2