如何将多重条件重新编码为 -1/0/+1?
How to recode multiple-conditionals to -1/0/+1?
我的数据如下:
Name A B C
apple 1 -1 0
banana 2 -2 1
pear -3 0 1
我想将所有正值替换为 -1,将所有负值替换为 +1,但将 0 保留为 0,我该如何实现?
我们可以使用 sign
来获取数据帧所有元素的符号,然后通过将其乘以 -1 来反转它。
df[-1] <- sign(df[-1]) * -1
df
# Name A B C
#1 apple -1 1 0
#2 banana -1 1 -1
#3 pear 1 0 -1
来自?sign
sign returns a vector with the signs of the corresponding elements of x (the sign of a real number is 1, 0, or -1 if the number is positive, zero, or negative, respectively).
数据
df <- structure(list(Name = structure(1:3, .Label = c("apple", "banana",
"pear"), class = "factor"), A = c(-1, -1, 1), B = c(1, 1, 0),
C = c(0, -1, -1)), .Names = c("Name", "A", "B", "C"), row.names = c(NA,
-3L), class = "data.frame")
这绝不与投票最高的一样好,但这里有一个替代方案:
ans <- df1[,-1] / -abs(df1[,-1])
ans[sapply(ans,is.nan)] <- 0
#> ans
# A B C
#1 -1 1 0
#2 -1 1 -1
#3 1 0 -1
我的数据如下:
Name A B C
apple 1 -1 0
banana 2 -2 1
pear -3 0 1
我想将所有正值替换为 -1,将所有负值替换为 +1,但将 0 保留为 0,我该如何实现?
我们可以使用 sign
来获取数据帧所有元素的符号,然后通过将其乘以 -1 来反转它。
df[-1] <- sign(df[-1]) * -1
df
# Name A B C
#1 apple -1 1 0
#2 banana -1 1 -1
#3 pear 1 0 -1
来自?sign
sign returns a vector with the signs of the corresponding elements of x (the sign of a real number is 1, 0, or -1 if the number is positive, zero, or negative, respectively).
数据
df <- structure(list(Name = structure(1:3, .Label = c("apple", "banana",
"pear"), class = "factor"), A = c(-1, -1, 1), B = c(1, 1, 0),
C = c(0, -1, -1)), .Names = c("Name", "A", "B", "C"), row.names = c(NA,
-3L), class = "data.frame")
这绝不与投票最高的一样好,但这里有一个替代方案:
ans <- df1[,-1] / -abs(df1[,-1])
ans[sapply(ans,is.nan)] <- 0
#> ans
# A B C
#1 -1 1 0
#2 -1 1 -1
#3 1 0 -1