简体   繁体   English

检查并替换R数据框中的列值

[英]Check and replace column values in R dataframe

I have multiple files to read in using R. I iterate through the files in a loop, obtain dataframes and then try to change values of a particular column. 我有多个文件需要使用R读取。我循环遍历文件,获取数据帧,然后尝试更改特定列的值。 Examples of the R dataframes are as follows: R数据帧的示例如下:

df_A: DF_A:

ID  ZN
1   0
2   1
3   1
4   0

df_B: DF_B:

ID  ZN
1   2
2   1
3   1
4   2

As shown above, the column 'ZN' for some dataaframes may have 0's and 1's and others dataframes have have 1's and 2's. 如上所示,某些数据帧的列“ ZN”可能具有0和1,而其他数据帧则具有1和2。 What I want is - as I'm iterating through the files, I want to make changes only in the dataframes with column ZN having 1's and 2's like this: 1 to 0 and 2 to 1. Dataframes with ZN values as 0's and 1's will be left unchaged. 我想要的是-当我遍历文件时,我只想对ZN列具有1和2的数据帧进行更改,如下所示:1到0和2到1。将ZN值为0和1的数据帧进行更改放任不管。

my attempt did not work: 我的尝试没有用:

if(dataframe$ZN > 1){
    dataframe$ZN<-recode(dataframe$ZN,"1=0;2=1")
  }
  else{
  dataframe$ZN
  }

Any solutions please? 有什么解决办法吗?

One approach might be to decrement the value of ZN by one if we detect a single value of 2 anywhere in the column: 如果我们在列中的任何位置检测到单个2值,则一种方法可能是将ZN值减1:

if (max(df_A$ZN) == 2) {
    df_A$ZN = df_A$ZN - 1
}

Demo 演示

If there are only two values ie 0 and 1, then 如果只有两个值,即0和1,则

df_A$ZN <- (df_A$ZN==0) + 1
df_A$ZN
#[1] 2 1 1 2

Or using case_when for multiple values 或对多个值使用case_when

library(dplyr)
df_A %>%
  mutate(ZN = case_when(ZN==0 ~2, TRUE ~ 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM