在DF

时间:2016-10-12 03:15:26

标签: r replace dataframe

我有一个如下所示的数据框:

  x1 y1 z1 x2 y2 z2
1  6  7  8  5  4 10
2  7  8  9  6  5 11
3  8  9 10  7  6 12
4  9 10 11  8  7 13
5 10 11 12  9  8 14
6 11 12 13 10  9 15

现在我想根据此规则更改x1和x2中的值:x1或x2中大于8的每个值都应减去8,x1或x2中的每个值都小于8或较小的应该用NA代替。另外,如果x1或x2中的值被NA y1 / y2替换,则z1 / z2也应设置为NA。数据框应如下所示。

  x1   y1 z1 x2 y2 z2
1  NA  NA NA NA NA NA
2  NA  NA NA NA NA NA
3  NA  NA NA NA NA NA
4   1 10 11  NA NA NA
5   2 11 12   1  8 14
6   3 12 13   2  9 15

生成数据帧的代码

df1<-data.frame("x1"=6:11,"y1"=7:12,"z1"=8:13,"x2"=5:10,"y2"=4:9,"z2"=10:15)

3 个答案:

答案 0 :(得分:1)

我们根据'x1'和'x2'创建两个索引,并根据这些索引分配值

i1 <- df1$x1 <=8 #x1 index
i2 <- df1$x2 <=8 #x2 index
nm1 <- grep("1$", names(df1)) #column index for suffix 1 in column names
nm2 <- grep("2$", names(df1)) #column index for suffix 2 in column names


df1[i1,nm1] <- NA #set the values for suffix 1 columns to NA
df1[i2, nm2] <- NA #set the values for suffix 2 columns to NA
df1[c('x1', 'x2')] <- df1[c('x1', 'x2')] - 8 #subtract 8 from the 'x' columns
df1
#   x1 y1 z1 x2 y2 z2
#1 NA NA NA NA NA NA
#2 NA NA NA NA NA NA
#3 NA NA NA NA NA NA
#4  1 10 11 NA NA NA
#5  2 11 12  1  8 14
#6  3 12 13  2  9 15

答案 1 :(得分:0)

我们有两个变量的条件,然后在这种情况下的一系列反应是真的。

# Activate the condition for x1 and x2
df1$x1 <- ifelse(df1$x1 > 8, df1$x1 - 8, NA)
df1$x2 <- ifelse(df1$x2 > 8, df1$x2 - 8, NA)

# Reaction of other variables to a external condition
df1$y1 <- ifelse(df1$x1 > 8, NA, df1$y1)
df1$y2 <- ifelse(df1$x2 > 8, NA, df1$y2)

# Reaction of other variables to a external condition
df1$z1 <- ifelse(df1$x1 > 8, NA, df1$z1)
df1$z2 <- ifelse(df1$x2 > 8, NA, df1$z2)

答案 2 :(得分:0)

library(dplyr)

df[,c("x1","x2")] <- sapply(df[,c("x1","x2")],function(x)ifelse(x>8,x-8,NA))


df %>%
  mutate(y1=replace(y1,which(x1%in%NA),NA))%>%
   mutate(z1=replace(z1,which(x1%in%NA),NA))%>%
  mutate(y2=replace(y2,which(x2%in%NA),NA))%>%
  mutate(z2=replace(z2,which(x2%in%NA),NA))

  x1 y1 z1 x2 y2 z2
1 NA NA NA NA NA NA
2 NA NA NA NA NA NA
3 NA NA NA NA NA NA
4  1 10 11 NA NA NA
5  2 11 12  1  8 14
6  3 12 13  2  9 15