Excel与R dataframe中的列操作类似

时间:2012-04-25 22:08:08

标签: r dataframe

我试图复制我在Excel中使用R做的一些建模。我已经将csv文件中的数据读入数据帧。 csv文件包含两列数据 A B

我现在想在数据框中添加其他列 C D E ,并填充新列C,D和E通过将公式应用于前一列中的数据生成的数据。

下面的代码段应该有助于澄清我尝试做的事情:

       A       B        C                   D              E
1    100.5   101.3
2    102.6   102.5
3    107.2   109.3
4    99.3    89.3
5    102.8   100.7     =(B5-B1)*A5         = C5           = IF(D5 >100,1,-1)
6    107.2   98.9      =(B6-B2)*A6         = C6+C5        = IF(D6 >100,1,-1)
7    99.8    109.9     =(B7-B3)*A7         = C7+C6        = IF(D7 >100,1,-1)
8    108.2   99.5      =(B8-B4)*A8         = C8+C7        = IF(D8 >100,1,-1)
9    78.7    89.6      =(B9-B5)*A9         = C9+C8        = IF(D9 >100,1,-1)
10   108.9   109.2     =(B10-B6)*A10       = C10+C9       = IF(D10 >100,1,-1)

我怎样才能复制这种"柱状" Excel(ahem - Excels)的函数式编程 - 使用R?

2 个答案:

答案 0 :(得分:9)

我的大脑在抗议下这样做。这让我觉得我回到Minitab会议。

 dfrm$C <- NA
 dfrm$C[5:10] <- with(dfrm, (B[5:10]-B[1:6])*A[5:10])
 dfrm$D <- NA
 dfrm$D[5:10] <- cumsum(dfrm$C[5:10])
 dfrm$E <- NA
 dfrm$E[5:10] <- 1 - 2*(dfrm$D[5:10] <= 100) # could also use ifelse()

dfrm
       A     B       C       D  E
1  100.5 101.3      NA      NA NA
2  102.6 102.5      NA      NA NA
3  107.2 109.3      NA      NA NA
4   99.3  89.3      NA      NA NA
5  102.8 100.7  -61.68  -61.68 -1
6  107.2  98.9 -385.92 -447.60 -1
7   99.8 109.9   59.88 -387.72 -1
8  108.2  99.5 1103.64  715.92  1
9   78.7  89.6 -873.57 -157.65 -1
10 108.9 109.2 1121.67  964.02  1

答案 1 :(得分:1)

我通过将BondedDust和Justin提供的答案结合到我的解决方案中,创建了以下正确的解决方案:

A <- c(100.5, 102.6, 107.2, 99.3, 102.8, 107.2, 99.8, 108.2, 78.7, 108.9)
B <- c(101.3, 102.5, 109.3, 89.3, 100.7, 98.9, 109.9, 99.5, 89.6, 109.2)
dfexcel <- data.frame(A, B, C = rep_len(NA, 10), D = rep_len(NA, 10), E = rep_len(NA, 10))
dfexcel$C[5:10] <- with(dfexcel, diff(B, lag=4)*A[5:10])
dfexcel$D[5:10] <- with(dfexcel, (C[5:10]+c(0,C[5:9]))) # cumsum doesn't work for D
dfexcel$E[5:10] <- ifelse(dfexcel$D[5:10] > 100, 1, -1)

这是LibreOffice Calc / Gnumeric / Microsoft Excel /等中的结果:

A   B   C   D   E
1   100.5   101.3           
2   102.6   102.5           
3   107.2   09.3            
4   99.3    89.3            
5   102.8   100.7   -61.68  -61.68  -1
6   107.2   98.9    -385.92 -447.6  -1
7   99.8    109.9   59.88   -326.04 -1
8   108.2   99.5    1103.64 1163.52 1
9   78.7    89.6    -873.57 230.07  1
10  108.9   109.2   1121.67 248.1   1