如何更新(分配新值)到存储在列表中的 R 数据帧 [英] How to update (assign new values) to R data frames stored in a list

查看:16
本文介绍了如何更新(分配新值)到存储在列表中的 R 数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# 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   

我想以矢量化的方式为每个数据帧的每一行分配一个 v1 的子字符串到 v2,例如,v2 = v1 的第三个字符,以获得这个:

I want to assign a substring of v1 to v2 for every row of every data frame in a vectorised manner, e.g., v2 = the third character of v1, to get this:

> df.list
[[1]]
   v1 v2
1 GNZ  Z
2 uCt  t
3 wed  d
4 3CA  A

[[2]]
   v1 v2
1 BhZ  Z
2 Aww  w
3 8pT  T
4 YYE  E

我知道这个 for 循环有效

I know this for-loop works

for (df in 1:2){
    df.list[[df]]$v2 = substr(df.list[[df]]$v1, 3, 3)
}
df.list

我知道我可以使用 rbind.fill(df.list) 然后设置 $v2 = substr($v1, 3, 3)

I know I could use rbind.fill(df.list) and then set $v2 = substr($v1, 3, 3)

我知道我可以在将数据框存储在列表中之前进行子字符串化,但我更愿意一次性全部子字符串化.

I know I could substring before storing the data frame in the list, but I'd rather substring all at once.

我想将数据保存在列表 b/c 中,该列表由将在其他代码中使用的字符串索引.rbind.fill 不保留索引/行名.

I'd like to keep the data in a list b/c the list is indexed by a string that will be used in other code. The rbind.fill does not keep the index / rowname.

我知道这行不通

sapply(df.list, "[[", "v2") <- sapply(df.list, function(x) substr(x$v1, 3,3))

即使右侧标识了正确的子字符串.我意识到左侧的 sapply 是一个输出函数,并不指向目标.但这传达了我正在尝试做的事情的想法.

Even though the right side identifies the correct substrings. I realize the sapply on the left side is an output function and does not point to the target. But this conveys the idea of what I'm trying to do.

这也生成子串 sapply(df.list, function(x) {x$v2 <- substr(x$v1,3,3)}) 但赋值没有得到制作.

This also generates the substring sapply(df.list, function(x) {x$v2 <- substr(x$v1,3,3)}) but the assignment does not get made.

那么我如何指向存储在列表中的每个结构等效数据框的同一列以矢量化方式进行分配?

So how do I point to the same column of every structurally equivalent data frame stored in a list to make the assignment in a vectorized manner?

推荐答案

使用 lapply 可以让您轻松地对列表中的每个元素应用函数.这是使用 lapplydplyrmutate 函数的解决方案.

Using lapply lets you apply functions easily over each element in a list. Heres a solution using lapply and dplyr's mutate function.

lapply(df.list, function(df) dplyr::mutate(df, v2=substr(v1,3,3)))

使用基础 R 的替代解决方案.

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)
})

这篇关于如何更新(分配新值)到存储在列表中的 R 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆