我有两列,如果一列在一行中有某个单词,我希望另一列在相应的行中添加 1 点

I have two columns, if one column has a certain word in a row, I'd like the other column to add 1 point to the corresponding row

我有一个包含字符串值的列和一个包含数值的列。如果字符串列中有某个单词,我想添加到每一行的数值

例如:

stringColumn  numericColumn 
----------------------------
yes            5
no             7
no             3
yes            4

numericColumn 中已经有随机数,但是在 运行 代码之后,如果 stringColumn = 'yes'.[=15,它应该向 numericColumn 添加 1 点=]

所以数据集最终看起来像这样

stringColumn  numericColumn 
----------------------------
yes            6
no             7
no             3
yes            5

您可以使用 mutate 中的 ifelse 语句编辑 numericColumn。因此,如果在 stringColumn 中(通过 str_detect)检测到 yes,则将 numericColumn 中的数字加 1,如果没有(即 no ), 然后 return numericColumn.

library(tidyverse)

df %>%
  mutate(numericColumn = ifelse(
    str_detect(stringColumn, "yes"),
    numericColumn + 1,
    numericColumn
  ))

输出

  stringColumn numericColumn
1          yes             6
2           no             7
3           no             3
4          yes             5

或以 R 为基数:

df$numericColumn <-
  ifelse(grepl("yes", df$stringColumn),
         df$numericColumn + 1,
         df$numericColumn)

数据

df <- structure(list(stringColumn = c("yes", "no", "no", "yes"), numericColumn = c(5L, 
7L, 3L, 4L)), class = "data.frame", row.names = c(NA, -4L))

有很多方法可以获得您想要的答案,但这是我对 tidyverse 版本的看法。条件语句在 case_when() 中进行,在 mutate() 中使用。值得一读 case_when() 的作用,因为它会派上用场用于各种用途。

library(tidyverse)

example_df <- tibble(
  stringColumn = c("yes", "no", "no", "yes"),
  numericColumn = c(5,7,3,4)
)

results_table <- example_df %>%
  mutate(
    Updated_column = case_when(
      stringColumn == "yes" ~ numericColumn + 1,
      TRUE ~ numericColumn
    )
  )


# option 1: print to console 
results_table 

# option 1.2: a tidier way to view on the console
glimpse(results_table)

# option 2: view on RStudio 
View(results_table)

# option 3: save as file (eg. .csv format)
write_csv(results_table, "path/to/folder/my_results.csv")