R数据帧:根据另一列中的值更改第一列中的值

时间:2020-06-22 14:02:42

标签: r dataframe

我有一个称为Nurse的数据框。目前,它包含几列,但目前仅涉及一列(nurse $ word)。我想创建一个名为Nurse $ w.frequency的新列,该列将查看Nurse $ word列中的单词,如果找到指定的单词,我希望它将相应的Nurse $ w.frequency值更改为指定的整数。

nurse <- read.csv(...)


file   word         w.frequency
1      determining
2      journey
3      journey
4      serving
5      work
6      journey
...    ...

例如,用于确定和行驶的单词频率分别是1590和4650。因此应如下所示:

file   word         w.frequency
1      determining  1590
2      journey      4650
3      journey      4650
4      serving
5      work
6      journey      4650
...    ...

我已经使用ifelse语句(如下)进行了尝试,该语句似乎起作用,但是,每次我尝试更改实际单词和频率时,它都会覆盖之前的结果。

nurse$w.frequency <- ifelse(nurse$word == "determining", nurse$w.frequency[nurse$word["determining"]] <- 1590, "")

2 个答案:

答案 0 :(得分:2)

您可以先初始化一个空列

nurse$w.frequency <- NA

然后用所需的数据填充

nurse$w.frequency[nurse$word == "determining"] <- 1590
nurse$w.frequency[nurse$word == "journey"] <- 4650

答案 1 :(得分:1)

使用dplyr

nurse %>% 
  mutate(w.frequency = 
           case_when(
             word == "determining" ~ "1590",
             word == "journey" ~ "4650",
             TRUE ~ ""
           ))

给我们:

         word w.frequency
1 determining        1590
2     journey        4650
3     journey        4650
4     serving            
5        work            
6     journey        4650

数据:

nurse <- data.frame(word = c("determining", "journey", "journey", "serving", "work", "journey"))