gpt4 book ai didi

r - 有条件地替换 R 中的分类值

转载 作者:行者123 更新时间:2023-12-05 03:11:10 25 4
gpt4 key购买 nike

我是 R 的新手,一直在这个论坛上咨询我以前遇到的一些 R 问题。但是,我似乎无法找到当前问题的答案。

我有一个包含多列的大数据集。我想根据另一列中的值替换一列中的某些值。这是一个示例:

organization                                    organization_type                
[1,] "Human Relief Foundation" "NGO"
[2,] "Management Systems International" "Other"
[3,] "World Vision" "NGO"
[4,] "European Disaster Volunteers" "NGO"
[5,] "Management Systems International" "Other"
[6,] "International Committee of the Red Cross" "Red Cross/Red Crescent Movement"
[7,] "International Committee of the Red Cross" "Red Cross/Red Crescent Movement"
[8,] "Development Alternatives" "Consultancy"

上面的数据集在 organization_type 下显示了“其他”的值“国际管理系统”。我想将“其他”替换为“咨询”。我该怎么做?

我已经按照另一个论坛中的建议尝试了以下方法,但它只保留了过滤后的数据:

library(dplyr)

data_df <- data_df %>% filter(organization == "Management Systems International"
& organization_type == "Other") %>%
mutate(organization_type = "Consultancy")

有没有办法在 R 中“取消过滤”数据,使原始数据条目与过滤后的数据一起出现? Excel 可以做到这一点,但很难在 Excel 中处理大数据集。

谢谢!

最佳答案

使用 data.table 包,您可以按如下方式执行此操作:

# Install if necessary
if (!require("data.table")) install.packages("data.table")
# Load the data.table package
library(data.table)

# Convert data_df to a data.table
data_dt <- data.table(data_df) %>%
# Where organization_type equals 'Other', replace organization_type to 'Consultancy'
.[organization_type == "Other", organization_type := "Consultancy"]

# Print result
print(data_dt)

结果:

                               organization               organization_type
1: Human Relief Foundation NGO
2: Management Systems International Consultancy
3: World Vision NGO
4: European Disaster Volunteers NGO
5: Management Systems International Consultancy
6: International Committee of the Red Cross Red Cross/Red Crescent Movement
7: International Committee of the Red Cross Red Cross/Red Crescent Movement
8: Development Alternatives Consultancy

关于r - 有条件地替换 R 中的分类值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902802/

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