gpt4 book ai didi

值在错误列中的 R 数据框

转载 作者:行者123 更新时间:2023-12-05 06:02:15 25 4
gpt4 key购买 nike

我有这样一个数据框:

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/

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