list - R:向数据框列表中的列添加不同的值

标签 list r add dataframe

如果我有这样一个列表:

list <- list( "1" = data.frame(time=1:3, temp = sample(11:13)),
              "3" = data.frame(time=1:3, temp = sample(11:13)))

list

$`1`
  time temp
1    1   11
2    2   12
3    3   13

$`3`
  time temp
1    1   11
2    2   12
3    3   13

现在我想为 temp 列添加一个校正值,数据帧 1 为 +1,数据帧 3 为 -1,因此结果为:

$`1`
  time temp
1    1   12
2    2   13
3    3   14

$`3`
  time temp
1    1   10
2    2   11
3    3   12

另外假设我有多个这样的列表,有时数据框 3 或 1 可能会丢失,甚至可能包含数据框 2,这需要其自己的校正因子... 我为数据框 1 尝试了一些奇怪的事情:

list <- lapply(list, function(x)   {x <- x$"1"$temp-1;x})

list <- lapply(list, function(x)   {x <- x[x$temp+1,];x})

还尝试为列表中的其他数据框添加一个 seq_along ...没有任何效果,可能是因为我不太了解语法的工作原理...

最佳答案

我把数据结构的名字改成了dflist。将列表称为“列表”是错误的。您还需要一些数据结构来引入相关的校正因子,所以让我们假设一个与“dflist”同名的数据结构:

dflist <- list( "1" = data.frame(time=1:3, temp = sample(11:13)),
              "3" = data.frame(time=1:3, temp = sample(11:13)))

corrlist <- list("1" = 1, "3"=-1) 

# Replaced lapply with for loop
for( nam in names(dflist)) {
        dflist[[nam]]['temp'] <- dflist[[nam]]['temp'] +corrlist[[nam]]
                            }
 dflist

关于list - R:向数据框列表中的列添加不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7124321/

相关文章:

python - Python 中 set() 中的 "add"操作或 dict() 中的 "insert"实际上是 O(n),其中 n 是 key 字符串的长度?

python - 如何添加不等长列表中的每个元素?

c# - 在 list<> 中拆分字符串值

python - 检查 csv 文件是否具有相同的项目

r - 使用 R 查找相关对

r - 读取单列 CSV 文件的更快方法

c++ - 获取单非循环链表中指针后面节点的值

r - Shiny 的 R DT : how to read/retain page length and column visibility

ios - 如何从两个 plist 中添加 NSMutableDictionary 中的信息?

android - Xamarin Android ExpandbleListView 添加子项