簡體   English   中英

根據另一列R中的字符創建一列

[英]Create a column based on characters from another column R

我希望根據另一列中存在的標簽創建一個新列。 舉一個簡單的例子,假設我有以下數據框

> df <- data.frame(label = c("AF1", "AF2", "AO1", "AO1"), somevalue = c(1, 2, 3, 4))
> df
  label somevalue
1   AF1         1
2   AF2         2
3   AO1         3
4   AO1         4

我需要做的是基於“標簽”中的中間字符創建一個新列。 我已經用下面的代碼做到了這一點,但是我覺得必須有一種更優雅的方式來做到這一點,而這是我目前無法做到的。

> df <- df %>% mutate(newCol = NA)
> df$newCol[str_detect(df$label, "F")] <- "fairies"
> df$newCol[str_detect(df$label, "O")] <- "ogres"
> df
  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

提前致謝。

您可以使用strsplit

df %>%
  mutate(newCol = map_chr(label, ~unlist(strsplit(., ""))[2])) %>%
  mutate(newCol = case_when(newCol == "F" ~ "fairies",
                            newCol == "O" ~ "ogres"))

  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

這是一個使用基本R代碼的簡單解決方案:

df[substr(df$label,2,2)=="F","newCol"]<-"fairies"
df[substr(df$label,2,2)=="O","newCol"]<-"ogres"
df
  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM