gpt4 book ai didi

r - 使用新创建的列中的值确定 x 列是否具有正值/负值/不同值

转载 作者:行者123 更新时间:2023-12-02 02:43:27 29 4
gpt4 key购买 nike

我正在尝试确定 x 列对于这些列中的值是否具有相同的方向(正或负)或者它们是否具有不同的方向(例如,一个为正,另一个为负)。

我目前正在使用 with确定列中的值是否为 > 0 , < 0或者在行中混合使用正数和负数。这很长而且效率不高,所以我想知道是否有更简单、更合适的方法来识别列在行中是否具有正值、负值或正负值的混合。


我已经尝试了使用下面的代码来执行此操作的冗长方法。这将创建多个列,然后我将这些列粘贴在一起以获得我的最后一列,告诉我 count1 和 count2 列是否均为正数、均为负数或方向不同。由于代码的长度,这仅适用于两列。

# make a data frame to demonstrate
data <- data.frame(count1 = c(1,-1,1,-1), count2 = c(1,-1,-1,1), count3 = c(1,-1,1,-1), count4 = c(1,-1,-1,1))

# if columns count1 and count2 are both less than 0 place a 1 in the new column, otherwise ""
data$direction_test1 <- with(data, ifelse(count1 < 0 & count2 < 0,
1, ""))
# if columns coun1 and coun2 are both greater than 0 place a 2 in the new column, otherwise ""
data$direction_test2 <- with(data, ifelse(count1 > 0 & count2 > 0,
2, ""))
# if columns count1 and count2 are different in direction (one is greater than 0 and the other less than 0) place a 0 in the new column, otherwise ""
data$direction_test3 <- with(data, ifelse(count1 > 0 & count2 < 0,
0, ""))
data$direction_test4 <- with(data, ifelse(count1 < 0 & count2 > 0,
0, ""))

# paste all of the columns together to make a single column
data$direction_test <- paste0(data$direction_test1, data$direction_test2, data$direction_test3, data$direction_test4)

我的数据框是这样的:

data <- data.frame(count1 = c(1,-1,1,-1), count2 = c(1,-1,-1,1), count3 = c(1,-1,1,-1), count4 = c(1,-1,-1,1))
  count1 count2 count3 count4 
1 1 1 1 1
2 -1 -1 -1 -1
3 1 -1 1 -1
4 -1 1 -1 1

我想知道每行中的所有值都是正值、负值还是混合值。新的数据框应该是这样的:

  count1 count2 count3 count4 direction
1 1 1 1 1 1
2 -1 -1 -1 -1 2
3 1 -1 1 -1 0
4 -1 1 -1 1 0

其中 1direction列表示计数列中的所有值都是正数,2direction列表示计数列中的所有值都是负数,并且 0在方向列中表示在计数列中存在正负值的混合。

最佳答案

这是一个基本的 R 选项:

data$direction <- sapply(1:nrow(data), function(x) ifelse(all(sign(data[x,]) == 1), 1, ifelse(all(sign(data[x,]) == -1), 2, 0)))
data

count1 count2 count3 count4 direction
1 1 1 1 1 1
2 -1 -1 -1 -1 2
3 1 -1 1 -1 0
4 -1 1 -1 1 0

关于r - 使用新创建的列中的值确定 x 列是否具有正值/负值/不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57606683/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com