# sample data options(stringsasfactors = false) set.seed(1) v1 = stringi::stri_rand_strings(4,3) v2 = rep("",4) df1 = data.frame(v1, v2) set.seed(2) v1 = stringi::stri_rand_strings(4,3) v2 = rep("",4) df2 = data.frame(v1, v2) df.list = list(df1,df2) df.list [[1]] v1 v2 1 gnz 2 uct 3 wed 4 3ca [[2]] v1 v2 1 bhz 2 aww 3 8pt 4 yye
i want assign substring of v1 v2 every row of every data frame in vectorised manner, e.g., v2 = third character of v1, this:
> df.list [[1]] v1 v2 1 gnz z 2 uct t 3 wed d 4 3ca [[2]] v1 v2 1 bhz z 2 aww w 3 8pt t 4 yye e
i know for-loop works
for (df in 1:2){ df.list[[df]]$v2 = substr(df.list[[df]]$v1, 3, 3) } df.list
i know use rbind.fill(df.list)
, set $v2 = substr($v1, 3, 3)
i know substring before storing data frame in list, i'd rather substring @ once.
i'd keep data in list b/c list indexed string used in other code. rbind.fill not keep index / rowname.
i know not work
sapply(df.list, "[[", "v2") <- sapply(df.list, function(x) substr(x$v1, 3,3))
even though right side identifies correct substrings. realize sapply on left side output function , not point target. conveys idea of i'm trying do.
this generates substring sapply(df.list, function(x) {x$v2 <- substr(x$v1,3,3)})
assignment not made.
so how point same column of every structurally equivalent data frame stored in list make assignment in vectorized manner?
using lapply
lets apply functions on each element in list. heres solution using lapply
, dplyr
's mutate
function.
lapply(df.list, function(df) dplyr::mutate(df, v2=substr(v1,3,3)))
alternate solutions using base r.
lapply(df.list, function(df) data.frame(v1=df$v1, v2=substr(df$v1,3,3))) lapply(df.list, function(df) { df$v2 <- substr(df$v1,3,3) return(df) })
Comments
Post a Comment