% mutate(category=subcategory) 结果与我正在寻找的结果接近,但它不包含第-6ren">
gpt4 book ai didi

r - 根据另一列更改一列的值(对于某些行)

转载 作者:行者123 更新时间:2023-12-04 12:36:40 24 4
gpt4 key购买 nike

我有一个数据框 df

ID <- c(1,2,3,4,5)
category <- c("Shirts", "Shirts", "Shirts", "Sweaters", "Sweaters")
subcategory <- c("V-Neck","V-Neck","Round","Striped","Striped")
df <- data.frame(ID,category,subcategory)

ID category subcategory
1 Shirts V-Neck
2 Shirts V-Neck
3 Shirts Round
4 Sweaters Striped
5 Sweaters Striped

我想将“子类别”列的名称分配给所有行的“类别”列,其中类别 ==“衬衫”

我的结果应该是这样的:

ID  category   subcategory
1 V-Neck V-Neck
2 V-Neck V-Neck
3 Round Round
4 Sweaters Striped
5 Sweaters Striped

我试过了

library(dplyr)
res <- df %>%
filter(category=="Shirts") %>%
mutate(category=subcategory)

结果与我正在寻找的结果接近,但它不包含第 4 行和第 5 行。

有人可以帮我解决这个问题吗?

最佳答案

不确定您是否正在寻找仅“dplyr”的答案(您的问题没有被标记为这样),但这对于“data.table”来说非常简单:

library(data.table)
as.data.table(df)[category == "Shirts", category := subcategory][]
# ID category subcategory
# 1: 1 V V
# 2: 2 V V
# 3: 3 Round Round
# 4: 4 Sweaters Striped
# 5: 5 Sweaters Striped

我想用“dplyr”,你可以试试ifelse(也可能是replace):

df[-1] <- lapply(df[-1], as.character)  ## Convert factors to characters
df %>%
mutate(category = ifelse(category == "Shirts",
subcategory, category))

关于r - 根据另一列更改一列的值(对于某些行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812609/

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