我有一个数据框:
A B C D E F G H
a LOW 1.5 0.2 NA 1000 2000 NA
b LOW 2.9 0.4 HIGH 6000 1000 NA
c LOW 1 1.3 LOW 400 1111 LOW
d LOW 2 10 LOW 1000 400 HIGH
如何使用条件语句替换NA
值。
对于E列,我想取C列和D列的差值,如果小于0,则显示“小减小”,如果大于0,则显示“小增加”。
然后对于H列,除了使用F列和G列的差异外,做同样的事情。如果低于0,则显示“小减少”,如果高于0,则显示“小增加”。
最终输出应如下所示:
A B C D E F G H
a LOW 1.5 0.2 Small Increase 1000 2000 Small Decrease
b LOW 2.9 0.4 HIGH 6000 1000 Small Increase
c LOW 1 1.3 LOW 400 1111 LOW
d LOW 2 10 LOW 1000 400 HIGH
答案 0 :(得分:3)
也为其他专栏执行类似的步骤!
df$E <- ifelse(is.na(df$E), ifelse(df$C-df$D <0,"small decrease","small increase"), df$E)
答案 1 :(得分:0)
以下是使用 if($scope.categories.length === 0){
console.log("No categories");
}
set
的选项,因为它可以非常有效地分配价值
data.table
library(data.table)
setDT(df1)#converts 'data.frame' to 'data.table'
#loop through the index of the concerned columns
for(j in c(5L, 8L)) {
#get the row index of NA for each column
i1 <- which(is.na(df1[[j]]))
#get the value to be replaced based on the difference
val <- c("Small Increase", "Small Decrease")[((df1[[j-2]][i1] - df1[[j-1]][i1]) < 0) + 1]
#set the NA elements to the above val
set(df1, i = i1, j = j, value = val)
}
df1
# A B C D E F G H
#1: a LOW 1.5 0.2 Small Increase 1000 2000 Small Decrease
#2: b LOW 2.9 0.4 HIGH 6000 1000 Small Increase
#3: c LOW 1.0 1.3 LOW 400 1111 LOW
#4: d LOW 2.0 10.0 LOW 1000 400 HIGH