gpt4 book ai didi

r - 如何根据R中同一列中的两个值改变新列

转载 作者:行者123 更新时间:2023-12-04 07:21:25 27 4
gpt4 key购买 nike

我想创建一个新列,如果列中一组的长度大于 25,则将其归类为不同,如果不是,则将其归类为相同。
例如,我有一个数据表:

#    read   condition   type      
#1 1 square 100
#2 1 square 100
#3 1 square 100
#4 1 round 200
#5 1 round 200
#6 1 round 200
#7 2 square 150
#8 2 square 150
#9 2 round 160
#10 2 round 160
我在思考伪代码:
data <- data %>%
group_by(read, condition) %>%
mutate(length = if_else("type of condition" == "round" > 25, different, same))
使用 dplyr,但我不确定如何选择组以产生此结果。由于这只是数据的一部分(读取 1 和 2),我需要一种可以应用于包含相同“正方形”和“圆形”条件的 read = 3、4、5 等的方法。这对基本 R 或 dplyr 可行吗?
想要的结果:
#    read   condition   type      length
#1 1 square 100 different
#2 1 square 100 different
#3 1 square 100 different
#4 1 round 200 different
#5 1 round 200 different
#6 1 round 200 different
#7 2 square 150 same
#8 2 square 150 same
#9 2 round 160 same
#10 2 round 160 same

最佳答案

我们可能需要获取 sum逻辑表达式

library(dplyr)
data %>%
group_by(read) %>%
mutate(length = if_else(sum(condition == "round",
na.rm = TRUE) > 25, # condition
"different", # true
"same") # false
)

关于r - 如何根据R中同一列中的两个值改变新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68475664/

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