R:如何有条件地替换数据框中的值

8,988 阅读2分钟

你可以使用以下方法之一来有条件地替换数据框中的值。

方法1:替换整个数据框中的值

#replace all values in data frame equal to 30 with 0
df[df == 30] <- 0

方法2:替换特定列中的值

#replace values equal to 30 in 'col1' with 0
df$col1[df$col1 == 30] <- 0

方法3:基于另一列替换特定列中的值

#replace values in col2 with 0 based on rows in col1 equal to 30
df$col2[df$col1 == 30] <- 0 

下面的例子说明了在实践中如何使用以下数据框中的每种方法。

#create data frame
df <- data.frame(team=c('A', 'A', 'B', 'B', 'B'),
                 points=c(99, 90, 90, 88, 88),
                 assists=c(33, 28, 31, 30, 34),
                 rebounds=c(30, 30, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    A     90      28       30
3    B     90      31       24
4    B     88      30       24
5    B     88      34       28

方法1:替换整个数据框中的值

下面的代码显示了如何将数据框中所有等于30的值替换为0。

#replace all values in data frame equal to 30 with 0
df[df == 30] <- 0

#view updated data frame
df
  team points assists rebounds
1    A     99      33        0
2    A     90      28        0
3    B     90      31       24
4    B     88       0       24
5    B     88      34       28

方法2:替换特定列中的值

下面的代码显示了如何用0替换 "点 "列中所有等于90的值。

#replace all values equal to 90 in 'points' column with 0
df$points[df$points == 90] <- 0

#view updated data frame
df

  team points assists rebounds
1    A     99      33       30
2    A      0      28       30
3    B      0      31       24
4    B     88      30       24
5    B     88      34       28

方法3:根据另一列替换特定列中的值

下面的代码显示了如何在 "团队 "列的值等于 "B "的情况下将 "积分 "列中的值替换为0。

#replace all values equal to 90 in 'points' column with 0
df$points[df$team == 'B'] <- 0

#view updated data frame
df

  team points assists rebounds
1    A     99      33       30
2    A     90      28       30
3    B      0      31       24
4    B      0      30       24
5    B      0      34       28

其他资源

下面的教程解释了如何在R中执行其他常见操作。

R:如何基于多列合并数据框架
R:如何基于其他列向数据框架添加列

The postR: How to Replace Values in Data Frame Conditionallyappeared first onStatology.