R: create new column and value using lapply & apply nested in data.frame, wrong output

I have a list of data frames (here is an example 2).

df1 <- read.table(text= "var,X2x,X4x,X6x
101337,4.631833,4.4547,11.097333
345754,3.727433,10.8560,10.536600" ,header=TRUE, sep=",")

 df2 <- read.table(text= "var,X2x,X4x,X6x
101337,5.631833,10.4547,11.097333
345754,5.727433,12.8560,10.536600" ,header=TRUE, sep=",")

dflist <- list(df1=df1, df2=df2)

I wanted to use lapply to go through each data.frame file, and use it for a simple comparison (i.e. check if the value from the second column is greater than the third), taking into account the result, add a new column with a tag (in the example, the new column is called " factor. ")

I'm almost there, but the output of my script is incorrect, returning a list of vectors instead of a list of data.frames with an added column.

here is the code:

dfL <- lapply(dflist,function(dfx) {
        apply(dfx,1, function(df) { if(df[3] < (df[4] )) {
      dfx$factor<-"nonNA"} else {dfx$factor<-"NA"}
      }
    )

}
)

Could you explain to me what I'm doing wrong?

+3
source share
2 answers

. -, dfx , <- <<-. . <<- (. ).

, , dfx apply, <<-, , , .

, apply dfx lapply.

transform , factor, 3- 4- (. ). , ifelse, apply:

lapply(dflist, transform, factor=ifelse(X4x < X6x, "nonNA", "NA"))

# $df1
# var      X2x     X4x      X6x factor
# 1 101337 4.631833  4.4547 11.09733  nonNA
# 2 345754 3.727433 10.8560 10.53660     NA
# 
# $df2
# var      X2x     X4x      X6x factor
# 1 101337 5.631833 10.4547 11.09733  nonNA
# 2 345754 5.727433 12.8560 10.53660     NA

, , , / , , , :

lapply(dflist, 
  function(dfx) {
    dfx$factor <- ""
    lapply(1:nrow(dfx), 
      function(row.id) {
        dfx[row.id, "factor"] <<- 
          if(dfx[row.id, 3] < dfx[row.id, 4]) "nonNA" else "NA"
    } )
    dfx
} )

, lapply apply, . , , .

+4

- . apply .

lapply(dflist, function(x){
  x$grp <- "not smaller"
  x$grp[x[ , 3] < x[ , 4]] <- "smaller"
  x
})

# $df1
#     var      X2x     X4x      X6x         grp
# 1 101337 4.631833  4.4547 11.09733     smaller
# 2 345754 3.727433 10.8560 10.53660 not smaller
# 
# $df2
#      var      X2x     X4x      X6x         grp
# 1 101337 5.631833 10.4547 11.09733     smaller
# 2 345754 5.727433 12.8560 10.53660 not smaller
+2

All Articles