新的数据帧cointaning另一列的列,R

时间:2016-09-21 11:09:38

标签: r dataframe

我有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) 

我认为我必须应用一些循环或应用的东西,但我不知道如何。

我想从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

1 个答案:

答案 0 :(得分:1)

请参阅代码中的注释。本质上,您编写了一个应该在每个data.frame上执行的函数,并使用它lapplysapply对每个data.frame执行此操作。由于您将这些data.frames放入列表中,因此使用lapplysapply非常方便。

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