R 将多个值字段转换为因子
从csv文件读取输入会给我留下一个包含多个值的奇数字段,例如R 将多个值字段转换为因子,r,R,从csv文件读取输入会给我留下一个包含多个值的奇数字段,例如 Title Genres 1 A [Item1, Item2, Item3] 2 B 3 C [Item4, Item1] df <- data.frame(c("A","B","C"), c("[Item1, Item2, Item3]","","[Item4, Item1]"), st
Title Genres
1 A [Item1, Item2, Item3]
2 B
3 C [Item4, Item1]
df <- data.frame(c("A","B","C"), c("[Item1, Item2, Item3]","","[Item4, Item1]"),
stringsAsFactors = FALSE)
colnames(df) <- c("Title","Genres")
标题类型
1A[项目1、项目2、项目3]
2 B
3 C[项目4,项目1]
df我不确定这是否正是您想要的,但我的做法有点不同。我使用了dplyr和grepl:
df <- data.frame(c("A","B","C"), c("[Item1, Item2, Item3]","","[Item4, Item1]"),
stringsAsFactors = FALSE)
colnames(df) <- c("Title","Genres")
df
df1<-df%>%
mutate(Item1 = ifelse(grepl("Item1",Genres), T,F),
Item2 = ifelse(grepl("Item2",Genres), T,F),
Item3 = ifelse(grepl("Item3",Genres), T,F),
Item4 = ifelse(grepl("Item4",Genres), T,F))
Title Genres Item1 Item2 Item3 Item4
1 A [Item1, Item2, Item3] TRUE TRUE TRUE FALSE
2 B FALSE FALSE FALSE FALSE
3 C [Item4, Item1] TRUE FALSE FALSE TRUE
df我不确定这是否正是您想要的,但我的做法有点不同。我使用了dplyr和grepl:
df <- data.frame(c("A","B","C"), c("[Item1, Item2, Item3]","","[Item4, Item1]"),
stringsAsFactors = FALSE)
colnames(df) <- c("Title","Genres")
df
df1<-df%>%
mutate(Item1 = ifelse(grepl("Item1",Genres), T,F),
Item2 = ifelse(grepl("Item2",Genres), T,F),
Item3 = ifelse(grepl("Item3",Genres), T,F),
Item4 = ifelse(grepl("Item4",Genres), T,F))
Title Genres Item1 Item2 Item3 Item4
1 A [Item1, Item2, Item3] TRUE TRUE TRUE FALSE
2 B FALSE FALSE FALSE FALSE
3 C [Item4, Item1] TRUE FALSE FALSE TRUE
df您可以使用Uwe建议的函数separate()
,但您的类型顺序似乎并不总是相同的。一个选项是使用mutate()
创建新列,并使用函数grepl()
来标识每个标记是否存在
df %>%
mutate(
Item1 = grepl('Item1', Genres),
Item2 = grepl('Item2', Genres),
Item3 = grepl('Item3', Genres),
Item4 = grepl('Item4', Genres)
)
# Title Genres Item1 Item2 Item3 Item4
# 1 A [Item1, Item2, Item3] TRUE TRUE TRUE FALSE
# 2 B FALSE FALSE FALSE FALSE
# 3 C [Item4, Item1] TRUE FALSE FALSE TRUE
您可以使用Uwe建议的函数separate()
,但您的类型顺序似乎并不总是相同的。一个选项是使用mutate()
创建新列,并使用函数grepl()
来标识每个标记是否存在
df %>%
mutate(
Item1 = grepl('Item1', Genres),
Item2 = grepl('Item2', Genres),
Item3 = grepl('Item3', Genres),
Item4 = grepl('Item4', Genres)
)
# Title Genres Item1 Item2 Item3 Item4
# 1 A [Item1, Item2, Item3] TRUE TRUE TRUE FALSE
# 2 B FALSE FALSE FALSE FALSE
# 3 C [Item4, Item1] TRUE FALSE FALSE TRUE
预期的结果是什么?也许,这个问题很有帮助?@Uwe感谢您的链接。我刚才搜索的是什么?预期的结果是什么?也许,这个问题很有帮助?@Uwe谢谢你的链接。正是我在寻找的