值在错误列中的 R 数据框

标签 r dplyr tidyverse

我有这样一个数据框:

Name Characteristic_1 Characteristic_2 
Apple Yellow Italian
Pear British Yellow
Strawberries French Red
Blackberry Blue Austrian

如您所见,特征可以根据行位于不同的列中。我想获得一个数据框,其中每列仅包含特定特征的值。

Name Characteristic_1 Characteristic_2 
Apple Yellow Italian
Pear  Yellow British
Strawberries Red French
Blackberry Blue Austrian

我的想法是使用 case_when 函数,但我想知道是否有更快的方法来实现相同的结果。

示例数据:

df <- structure(list(Name = c("Apple", "Pear", "Strawberries", "Blackberry"
), Characteristic_1 = c("Yellow", "British", "French", "Blue"
), Characteristic_2 = c("Italian", "Yellow", "Red", "Austrian"
)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
))

最佳答案

我怀疑有更简单的方法来解决这个问题,但这里有一个可能的解决方案:

# Load the libraries
library(tidyverse)

# Load the data
df <- structure(list(Name = c("Apple", "Pear", "Strawberries", "Blackberry"
), Characteristic_1 = c("Yellow", "British", "French", "Blue"
), Characteristic_2 = c("Italian", "Yellow", "Red", "Austrian"
)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
))

# R has 657 built in colour names. You can see them using the `colours()` function.
# Chances are your colours are contained in this list.
# The `str_to_title()` function capitalizes every colour in the list
list_of_colours <- str_to_title(colours())
# If your colours are not contained in the list, add them using e.g.
# `list_of_colours <- c(list_of_colours, "Octarine")`

# Create a new dataframe ("df2") by taking the original dataframe ("df")
df2 <- df %>% 
# Create two new columns called "Colour" and "Origin" using `mutate()` with
# `ifelse` used to identify whether each word is in the list of colours.
# If the word is in the list of colours, add it to the "Colours" column, if
# it isn't, add it to the "Origin" column.
  mutate(Colour = ifelse(!is.na(str_extract(Characteristic_1, paste(list_of_colours, collapse = "|"))),
                       Characteristic_1, Characteristic_2),
         Origin = ifelse(is.na(str_extract(Characteristic_1, paste(list_of_colours, collapse = "|"))),
                         Characteristic_1, Characteristic_2)) %>% 
# Then select the columns you want
  select(Name, Colour, Origin)

df2
# A tibble: 4 x 3
#  Name         Colour Origin  
#  <chr>        <chr>  <chr>   
#1 Apple        Yellow Italian 
#2 Pear         Yellow British 
#3 Strawberries Red    French  
#4 Blackberry   Blue   Austrian

关于值在错误列中的 R 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66976840/

相关文章:

r - 为列名传递变量?

r - 分组 case_when 返回重复行

r - R 的新原生管道 `|>` 和 magrittr 管道 `%>%` 有什么区别?

r - 如何在基本 R 公式中使用类似 quosure 的语法?

r - 如何将二元组拆分为 n 列的列对和行对

R:使用组引用计算行中值之间的差异

r - 通过强制引入 NA 时如何避免警告

r - 如何使用 R 的 xlsx 包对齐 XLSX 文件的单元格?

r - 在大字段中搜索值时,如果字段已排序,效率会有所不同吗

r - 如何基于列聚合数据