根据以下流行趋势进行基本添加

时间:2019-06-14 11:17:57

标签: r

我必须按照以下方式计算分数。

ITEMS                   A   B   C   E   F   G   H   I   J   K
COLLECTION              10  10  10  10  10  10  10  10  10  10
FINAL CALCULATION           10  20  30  40  50  60  70  80  90

在这里,对于A,第一轮有10个项目集合,其最终计算将为空白;对于B,其最终集合将为10,因此最终计算将为10,然后对于C,其之前的最终计算将是当前的计算。所以C = 10 + B的最终校准= 10 + 10 = 20

与D相同,10 + 20 = 30,D =30。

集合可以随机更改,只是df中应考虑的一行。

dput(df)
structure(list(X = structure(2:1, .Label = c("collection", "item"
), class = "factor"), V1 = structure(2:1, .Label = c("10", "A"
), class = "factor"), V2 = structure(2:1, .Label = c("20", "A"
), class = "factor"), V3 = structure(2:1, .Label = c("10", "A"
), class = "factor"), V4 = structure(2:1, .Label = c("20", "A"
), class = "factor"), V5 = structure(2:1, .Label = c("10", "A"
), class = "factor"), V6 = structure(2:1, .Label = c("20", "A"
), class = "factor"), V7 = structure(2:1, .Label = c("10", "A"
), class = "factor"), V8 = structure(2:1, .Label = c("10", "A"
), class = "factor"), V9 = structure(2:1, .Label = c("20", "A"
), class = "factor"), V10 = structure(2:1, .Label = c("20", "A"
), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

my code : 
df <- data.frame(df)
df[2, ] <- c(NA, cumsum(unlist(df[1, 1:(ncol(df)-1)])))


Error: 
df[2, ] <- c(NA, cumsum(unlist(df[1, 1:(ncol(df)-1)])))
Error in Math.factor(unlist(df[1, 1:(ncol(df) - 1)])) :     
  ‘cumsum’ not meaningful for factors

2 个答案:

答案 0 :(得分:1)

如果我做对了,您要找的是一个累加的总和,但是对于第一个值,应该是一个na。

df <- data.frame(matrix(rep(10, 10), ncol= 10))

df[2, ] <- c(NA, cumsum(unlist(df[1, 1:(ncol(df)-1)])))

编辑

我不必是rep(10,10)。看到这里

set.seed(1)
df <- data.frame(matrix(sample(1:10, 5), ncol= 5))
df[2, ] <- c(NA, cumsum(unlist(df[1, 1:(ncol(df)-1)])))
df
  X1 X2 X3 X4 X5
1  3  4  5  7  2
2 NA  3  7 12 19

答案 1 :(得分:0)

# update columns to character
df = sapply(df, as.character)

# set as dataframe and keep the character columns values
df = data.frame(df, stringsAsFactors = F)

# add the new row at the bottom (using values from last row)
df[nrow(df)+1, ] <- as.character(c("FINAL CALCULATION", NA, cumsum(as.numeric(unlist(df[nrow(df), nrow(df):(ncol(df)-1)])))))

# view updated dataset
df

#                   X   V1 V2 V3 V4 V5 V6 V7  V8  V9 V10
# 1              item    A  A  A  A  A  A  A   A   A   A
# 2        collection   10 20 10 20 10 20 10  10  20  20
# 3 FINAL CALCULATION <NA> 10 30 40 60 70 90 100 110 130