数据帧列明智的减法和除法。

问题描述 投票:1回答:2

在N数或列式减法和除法中需要帮助,下面是输入数据帧中的列。

input dataframe:

> df
    A B C D
1   1 3 6 2
2   3 3 3 4
3   1 2 2 2
4   4 4 4 4
5   5 2 3 2


formula - a, (b - a) / (1-a)

MY CODE 
ABC <- cbind.data.frame(DF[1], (DF[-1] - DF[-ncol(DF)])/(1 - DF[-ncol(DF)]))

Expected out: 
  A    B     C    D
  1  Inf   -1.5  0.8
  3  0.00   0.0 -0.5
  1  Inf    0.0  0.0
  4  0.00   0.0  0.0
  5  0.75  -1.0  0.5

但是我不想在这里使用ncol,因为在实际数据帧中D列之后有一个最后一列。

所以想要只将这个公式应用到前4列,如果我使用ncol,它将遍历数据帧中的最后一列。请帮助谢谢。

r loops dataframe matrix apply
2个回答
2
投票

尝试怎么样:

df <- matrix(c(1,3,6,2,3,3,3,4,1,2,2,2,4,4,4,4,5,2,3,2), nrow = 5, byrow = TRUE)
df_2 <- matrix((df[,2]-df[,1])/(1-df[,1]),5,1)
df_3 <- matrix((df[,3]-df[,2])/(1-df[,2]),5,1)
df_4 <- matrix((df[,4]-df[,3])/(1-df[,3]),5,1)
cbind(df[,1],df_2,df_3,df_4)

编辑:循环版本

df <- matrix(c(1,3,6,2,3,3,3,4,1,2,2,2,4,4,4,4,5,2,3,2), nrow = 5, byrow = TRUE)
test_bind <- c()
test_bind <- cbind(test_bind, df[,1])
for (i in 1:3){df_1 <- matrix((df[,i+1]-df[,i])/(1-df[,i]),5,1)
    test_bind <- cbind(test_bind,df_1)}
    test_bind

0
投票

这是tidyverse的一个选项

library(dplyr)
library(purrr)
map2_df(DF[2:4], DF[1:3], ~ (.x - .y)/(1- .y)) %>%
        bind_cols(DF[1], .)
#  A    B    C    D
#1 1  Inf -1.5  0.8
#2 3 0.00  0.0 -0.5
#3 1  Inf  0.0  0.0
#4 4 0.00  0.0  0.0
#5 5 0.75 -1.0  0.5
© www.soinside.com 2019 - 2024. All rights reserved.