【问题标题】:New dataframe cointaning sum of column of another, R新的数据框与另一个列的总和,R
【发布时间】:2016-09-21 11:09:37
【问题描述】:

我有 32 个数据框,我需要为每个数据框获取一个新数据框,其中包含一些其他数据框列的总和。

让我写一个包含 2 个数据框的示例以更清楚:

df1 <- data.frame(1:5,2:6,3:7, 4:8)
colnames(df1) <- c("one", "two", "three", "four")
df2 <- data.frame(4:8, 5:9, 6:10, 7:11)
colnames(df2) <- c("one", "two", "three", "four")

我想得到的是一个数据框df1a,其中第1列是数据框df1的第1列和第3列之和,第2列是相同的,没有变化。我也想把第 4 列放在输出的第一位。

我知道我可以写这段代码:

df1a <- data.frame(df1$four, df1$one+df1$three, df1$two )
colnames(df1a) <- c("four", "1+3", "two")

但在我看来,为每个数据帧都写很长,因为在我的真实数据中,我有 32 个数据帧,每个数据帧由 20 列组成。

我把它们放在一个列表中:

listdf <- list(df1, df2) 

我想我必须使用 apply 来应用一些循环或其他东西,但我不知道如何。

我想从 df1 到 df1a 获得的示例:

df1
  one two three four
1   1   2     3    4
2   2   3     4    5
3   3   4     5    6
4   4   5     6    7
5   5   6     7    8

df1a <- data.frame(df1$four, df1$one+df1$three, df1$two )
colnames(df1a) <- c("four", "1+3", "two")
df1a
  four 1+3 two
1    4   4   2
2    5   6   3
3    6   8   4
4    7  10   5
5    8  12   6

【问题讨论】:

  • 查看 gregor 在this post 中关于使用 data.frames 列表的回答。我的回答为检索命名的 data.frames 列表提供了一个很好的快捷方式。
  • @RonakShah,添加了一个例子

标签: r dataframe


【解决方案1】:

查看代码中的 cmets。本质上,您编写了一个应该对每个 data.frame 执行的函数,并使用它lapply 或 sapply 对每个 data.frame 执行此操作。既然你把这些data.frames放到一个列表中,使用lapply或者sapply就很方便了。

df1 <- data.frame(1:5,2:6,3:7, 4:8)
colnames(df1) <- c("one", "two", "three", "four")
df2 <- data.frame(4:8, 5:9, 6:10, 7:11)
colnames(df2) <- c("one", "two", "three", "four")

# Create a function which holds commands to be used on a single data.frame
operationsPerDF <- function(x) {
  data.frame(four = x$four, onepthree = x$one + x$three, two = x$two)
}

# You can manually gather data.frames into a list.
lapply(list(df1, df2), FUN = operationsPerDF)

# Or find data.frames by a pattern, collect them into a list...
list.dfs <- sapply(ls(pattern = "df"), get, simplify = FALSE)

# ... and perform the above operation, one data.frame at a time
lapply(list.dfs, FUN = operationsPerDF)

$df1
  four onepthree two
1    4         4   2
2    5         6   3
3    6         8   4
4    7        10   5
5    8        12   6

$df2
  four onepthree two
1    7        10   5
2    8        12   6
3    9        14   7
4   10        16   8
5   11        18   9

【讨论】:

  • 我应用了函数,并使用了lapply(nameofmylist, FUN = operationsPerDF),但我丢失了列表中数据框的名称。有没有办法避免损失?
  • @Francesco 你如何构建nameofmylist?这可能是删除名称的步骤。
  • 这边:listdf &lt;- list(df1, df2) 。也许我应该为他们命名?
  • @Francesco 是的,您应该命名它们。如果有明确的模式,请尝试我的答案中的建议,您可以自动收集它们。在这种情况下命名会得到处理。
猜你喜欢
  • 2020-08-02
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 2019-08-12
相关资源
最近更新 更多