calculating average of two column in another column

I am trying to calculate the average of columns in another column but getting errror

converted all the nastring na.strings = c("N") to NA but after the class of columns is character.

after this i have NA in place of N in data frame but still the class of column is character

df <- data.frame("T_1_1"= c(68,24,"N",105,58,"N",135,126,24),
                 "T_1_2"=c(26,105,"N",73,39,97,46,108,"N"),
                 "T_1_3"=c(93,32,73,103,149,"N",147,113,139),
                 "S_2_1"=c(69,67,94,"N",77,136,137,92,73),
                 "S_2_2"=c(87,67,47,120,85,122,"N",96,79),
                 "S_2_3"= c(150,"N",132,121,29,78,109,40,"N"),
                 "TS1_av"=c(68.5,45.5,94,105,67.5,136,136,109,48.5),
                 "TS2_av"=c(56.5,86,47,96.5,62,109.5,46,102,79),
                 "TS3_av"=c(121.5,32,102.5,112,89,78,128,76.5,139)

)

df$TS1_av <- rowMeans(df[,c(as.numeric(as.character("T_1_1","S_2_1")))], na.rm=TRUE)

Are you trying to do something like this?

library(dplyr, warn.conflicts = FALSE)

df <- data.frame("T_1_1"= c(68,24,"N",105,58,"N",135,126,24),
                 "T_1_2"=c(26,105,"N",73,39,97,46,108,"N"),
                 "T_1_3"=c(93,32,73,103,149,"N",147,113,139),
                 "S_2_1"=c(69,67,94,"N",77,136,137,92,73),
                 "S_2_2"=c(87,67,47,120,85,122,"N",96,79),
                 "S_2_3"= c(150,"N",132,121,29,78,109,40,"N")
)
head(df)
#>   T_1_1 T_1_2 T_1_3 S_2_1 S_2_2 S_2_3
#> 1    68    26    93    69    87   150
#> 2    24   105    32    67    67     N
#> 3     N     N    73    94    47   132
#> 4   105    73   103     N   120   121
#> 5    58    39   149    77    85    29
#> 6     N    97     N   136   122    78
ConvertN <- function(Col) {
  Col <- ifelse(Col == "N", NA, Col)
  as.numeric(Col)
}
df <- df %>% mutate(across(.fns = ConvertN))
df$TS1_av <- rowMeans(df[,c("T_1_1","S_2_1")],na.rm = TRUE)
head(df)
#>   T_1_1 T_1_2 T_1_3 S_2_1 S_2_2 S_2_3 TS1_av
#> 1    68    26    93    69    87   150   68.5
#> 2    24   105    32    67    67    NA   45.5
#> 3    NA    NA    73    94    47   132   94.0
#> 4   105    73   103    NA   120   121  105.0
#> 5    58    39   149    77    85    29   67.5
#> 6    NA    97    NA   136   122    78  136.0

Created on 2021-04-17 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.