In R's data frame, please refer to the values in the next column and your own values in the same row and tell me which functions to replace!

Asked 2 years ago, Updated 2 years ago, 35 views

Replace R data frames by referring to the values in the next column of the same row and their own values.
Easy way
I would like you to tell me!

I would like to process it like the image below.
(My own mass == 1 & & 0 in the next column of the same row) Change my mass to 2

if (my own square==1&& next column in the same row, change my square to 2)

r

2022-09-30 21:47

2 Answers

This may be the extent of your imagination, but I'm not sure about the conditions after .

#Creating Data Frames
df<-rbind(c(NA,NA,1,1,1),
            c(1,0,0,0,0),
            c(1,1,0,0,0),
            c(1,1,1,0,0),
            c(NA,NA,1,0,0))

# Loop by number of rows
for(i in 1:nrow(df)){
  # Loop by column
  for(jin1:(ncol(df)-1){
    # NA determination of elements to be verified, TRUE if NA is not included
    if(!is.na(df[i,j])){
      # Determine if the element of df has 0 in the next column of 1
    if((df[i,j]==1)&(df[i,(j+1)] == 0)){
      # If TRUE, rewrite 1 to 2.
      df[i,j]<-2
    }
    }
  }
}

It contains NA elements, so processing is complicated.
Only the number of elements is checked in the loop, so the more elements you have, the slower the processing becomes.
Not very elegant.


2022-09-30 21:47

I think there are many ways to do it, but
Since it's R, how about using tidyverse?

"Reduce the amount of code you write" is your top priority.

table<-rbind(c(NA,NA,1,1,1),
            c(1,0,0,0,0),
            c(1,1,0,0,0),
            c(1,1,1,0,0),
            c(NA,NA,10,0))%>%as_tible

tumble%>%
  unite("combi", 1:ncol(tibble), sep="-")%>%
  mute(modified=str_replace_all(combi, "1-0", "2-0")))

Here's the result:

>tible%>%
+   unite("combi", 1:ncol(tibble), sep="-")%>%
+   mute(modified=str_replace_all(combi, "1-0", "2-0"))
# Atible: 2 x 5
  combined   
  <chr><chr>      
1 NA-NA-1-1-1 NA-NA-1-1-1
2 1-0-0-0-0   2-0-0-0-0  
3 1-1-0-0-0   1-2-0-0-0  
4 1-1-1-0-0   1-1-2-0-0  
5 NA-NA-1-0-0 NA-NA-2-0-0

Also, if you use separate() as needed, you can undo it in one line.

>colnames_bkp<-names(tibble)
> 
>tible%>%
+   unite("combi", 1:ncol(tibble), sep="-")%>%
+   mute(modified=str_replace_all(combi, "1-0", "2-0")%>%
+   separate("modified", into=colnames_bkp)
# Atible—6 x 5
  combi V1 V2 V3 V4 V5   
  <chr><chr><chr><chr><chr>
1 NA-NA-1-1-1 NA 11    
2 1-0-0-0-0   2     0     0     0     0    
3 1-1-0-0-0   1     2     0     0     0    
4 1-1-1-0-0   1     1     2     0     0    
5 NA-NA-1-0-0 NA 2000    

The combination of "unite()/separate()" can be used in many ways, so
Please enjoy a lot of things.


2022-09-30 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.