我有两列,weight
和area
。我想按如下方式创建两列:
weight
> 12,顶部,否则下来。area
> -0.5,插入值0.否则将area
的绝对值四舍五入为0.5,映射为1。期望的输出:
weight area out1 out2
12 3 down 0
13 -0.4 top 0
11 2.5 down 0
17 -0.5 top 1
16 -3.7 top 4
14 -1.2 top 1
11 -4.8 down 5
答案 0 :(得分:1)
尝试
transform(df, out1=c('down', 'top')[(weight>12)+1L],
out2= ifelse(area >-0.5, 0, abs(round2(area,0))))
# weight area out1 out2
#1 12 3.0 down 0
#2 13 -0.4 top 0
#3 11 2.5 down 0
#4 17 -0.5 top 1
#5 16 -3.7 top 4
#6 14 -1.2 top 1
#7 11 -4.8 down 5
或者
library(data.table)
setDT(df)[, paste0('out',1:2) := list(c('down', 'top')[(weight>12)+1L],
ifelse(area > -0.5, 0, abs(round2(area,0))))][]
其中round2
是(摘自Round up from .5 in R)
round2 = function(x, n) {
posneg = sign(x)
z = abs(x)*10^n
z = z + 0.5
z = trunc(z)
z = z/10^n
z*posneg
}
答案 1 :(得分:1)
以下是我使用data.table
:
require(data.table)
dt[, out1 := "down"][weight > 12, out1 := "top"]
dt[, out2 := floor(abs(area)+0.5)][area > -0.5, out2 := 0]
# weight area out1 out2
# 1: 12 3.0 down 0
# 2: 13 -0.4 top 0
# 3: 11 2.5 down 0
# 4: 17 -0.5 top 1
# 5: 16 -3.7 top 4
# 6: 14 -1.2 top 1
# 7: 11 -4.8 down 5
答案 2 :(得分:0)
df <- data.frame(weight= c(12, 13, 11, 17, 16, 14, 11),
area = c(3, -0.4, 2.5, -0.5, -3.7, -1.2, -4.8))
df$out1 <- ifelse(df$weight > 12, "top", "down")
df$out2 <- ifelse(df$area > -0.5, 0, floor(0.5 + abs(df$area)))
df
# weight area out1 out2
# 1 12 3.0 down 0
# 2 13 -0.4 top 0
# 3 11 2.5 down 0
# 4 17 -0.5 top 1
# 5 16 -3.7 top 4
# 6 14 -1.2 top 1
# 7 11 -4.8 down 5