r - Create a new column in dataframe by indexing into a list using another column? -
i have dataframe column of indices, , list maps each index value.
x <- data.frame( index = c("bob","tom","bob","harry") ) lst <- list( "bob" = 10, "tom" = 20, "harry" = 30 ) i create new column ("lookup") in dataframe using index column lookup appropriate value in list. thought ...
x$lookup <- lst[[ x$index ]] # nope, doesn't work ... might work, fails attempt of recursive indexing. following works, i'd avoid using loop if possible:
for (i in 1:nrow(x) ) { # works, ugly x[ i, "lookup" ] <- lst[[ as.character( x[i,"index"] ) ]] } yielding following desired result:
> x index lookup 1 bob 10 2 tom 20 3 bob 10 4 harry 30 is there way accomplish without using loop?
i caught surprise creating 'x' generated dataframe column of factors rather strings. is using 'as.character' in loop best way index list?
new both r , stackoverflow, posting first question after unsuccessfully trying search answer. apologies newness.
you can try match
x$lookup <- unlist(lst[match(x$index, names(lst))]) x # index lookup #1 bob 10 #2 tom 20 #3 bob 10 #4 harry 30 or use stack/merge
merge(x,stack(lst), by.x='index', by.y='ind')
Comments
Post a Comment