【问题标题】:How we could sort these data out in R我们如何在 R 中整理这些数据
【发布时间】:2021-05-14 20:07:57
【问题描述】:

这是我的数据示例:

   df<-read.table(text=" Colour Leave   Real
    Blue    Y   Yellow
    Red     N   NA
    Yellow  Y   NA
    Green   Y   Green
    Blue    N   NA
    Green   Y   Red
    Yellow  Y   Blue
    Green   Y   NA
    ",header=TRUE)

我想得到这个输出:

Colour1 Colour2
FALSE   Yellow
Red     FALSE
Blue    Yellow
FALSE   Green
Blue    FALSE
Red     FALSE
Blue    FALSE
Red     Green

逻辑 颜色 1 只得到蓝色和红色,颜色 2 只得到黄色和绿色。 蓝色对应黄色,红色对应绿色。 如果 Leave 是“Y”,我们看 Real,如果 Real 有颜色,我们选择这个颜色。例如,Row1,color=Blue,Leave=Y,Real=Yellow。所以我们在 colour2 中选择 Yellow 并且 Color 1 为 FALSE。 如果 Leave 为“N”,我们查看 Real,如果 Real 没有颜色,即 NA,我们在 Color Column 中选择颜色。例如,Row2,color=Red,Leave=N,Real=NA。所以我们在 colour1 中选择 Red,Color 2 为 FALSE。 如果 Leave 为“Y”,我们查看 Real,如果 Real 没有颜色,即 NA,我们选择两种颜色。例如,最后一行,颜色 = 绿色,离开 = Y 和真实 = NA。所以我们在 colour1 中选择 Red,Color 2 得到 Green。

【问题讨论】:

  • 您在 logic 解释中使用了很多 if。那么如何将它们放入R 中的ifelse 语句中呢?您还应该在 R 中使用 is.na()%in% 函数。请先把你的努力,问清楚你卡住的地方。

标签: r dplyr


【解决方案1】:

您可以执行以下操作:

df<-read.table(text=
" Colour Leave   Real
    Blue    Y   Yellow
    Red     N   NA
    Yellow  Y   NA
    Green   Y   Green
    Blue    N   NA
    Green   Y   Red
    Yellow  Y   Blue
    Green   Y   NA
    ",header=TRUE, stringsAsFactors = FALSE)
df$ind <- 1:nrow(df)

#labeling the rows based on the color conditions
df$cond_total <- 
  ifelse(df$Leave=="Y", #if leave is "Y
         ifelse(!is.na(df$Real),  #if real is not NA 
         "YV","YnV"),
         #if leave is "N"
         ifelse(!is.na(df$Real), #if real is not NA
          "NV", "NnV"))
#rules as specified:
#YV -> take just real
#YnV -> take colour and fill both colors 
#NV -> not specified
#NnV -> take just colour
#based on the the above rules, we reassign Real and Colour column
df$col <- ifelse(df$cond_total=="YV", df$Real, df$Colour)
df$keep_both <- ifelse(df$cond_total=="YnV", 1, 0)

#complementary colour addition
temp <- data.frame(col=c("Blue", "Red","Yellow","Green"), 
                   col_oposite=c("Yellow","Green","Blue", "Red"), 
                   stringsAsFactors = FALSE)
df <- merge(df, temp, by.x = "col", by.y = "col", all.x = TRUE)
df <- df[order(df$ind),]
df$col_oposite <- ifelse(df$keep_both==0, 'FALSE', df$col_oposite)

#final swapping of colours as needed
df$Colour1 <- ifelse(df$col %in% c("Blue","Red"), df$col, df$col_oposite)
df$Colour2 <- ifelse(df$col %in% c("Yellow","Green"), df$col, df$col_oposite)

此数据集中的列 Colour1 和 Color 2 形成所需的输出。

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多