gpt4 book ai didi

r - 用dplyr创建一个因子变量?

转载 作者:行者123 更新时间:2023-12-05 08:19:07 25 4
gpt4 key购买 nike

假设我有一个看起来像这样的数据框:

df1=structure(list(Name = structure(1:6, .Label = c("N1", "N2", "N3", 
"N4", "N5", "N6", "N7"), class = "factor"), sector = structure(c(4L,
4L, 4L, 3L, 3L, 2L), .Label = c("other stuff", "Private for-profit, 4-year or above",
"Private not-for-profit, 4-year or above", "Public, 4-year or above"
), class = "factor"), flagship = c(1, 0, 0, 0, 0, 0)), .Names = c("Name",
"sector", "flagship"), row.names = c(NA, 6L), class = "data.frame")

我想创建一个新的因子变量“Sector”。我可以用很多行代码来完成它,但我确信有一种更有效的方法。

现在这就是我正在做的:

df1$PublicFlag=0
df1$PublicFlag[df1$sector=="Public, 4-year or above" & df1$flagship==1]=1
df1$Public=0
df1$Public[df1$sector=="Public, 4-year or above" & df1$flagship==0]=1
df1$PrivateNP=0
df1$PrivateNP[df1$sector=="Private not-for-profit"]=1
df1$Private4P=0
df1$Private4P[df1$sector=="Private for-profit, 4-year or above"]=1

library(reshape)
df2 = melt(df1, id=c("Name", "sector", "flagship"))
df2 = df2[df2$value==1,c("Name", "sector", "flagship", "variable")]
library(plyr)
df2 = rename(df2, c("variable"="Sector"))

感谢您的帮助!

最佳答案

这是一个旧帖子,但我经常偶然发现它。这就是为什么我想给出一个最新的答案。 Version 0.5.0 of dplyr引入了很多有用的向量函数来解决这个问题。

使用 case_when() 避免 ifelse 嵌套(从而让很多很多小猫活着):

df1 %>% 
mutate(Sector = case_when(
sector=="Public, 4-year or above" & flagship==1 ~ "PublicFlag",
sector=="Public, 4-year or above" & flagship==0 ~ "Public",
sector=="Private not-for-profit" ~ "PrivateNP",
sector=="Private for-profit, 4-year or above" ~ "Private4P"),
Sector = factor(Sector, levels=c("Public","PublicFlag","PrivateNP","Private4P"))
)

使用 recode_factor() 从字符(或数字)变量生成因子:

df1 %>%
mutate(Sector = recode_factor(sector,
"Public, 4-year or above" = "Public",
"Private not-for-profit" = "PrivateNP",
"Private for-profit, 4-year or above" = "Private4P"))

关于r - 用dplyr创建一个因子变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26123516/

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