jeudi 2 septembre 2021

R - best way to apply an if statement on multiple arguments

Example: Let's say I have the two dataframes

DF1 = data.frame(V1 = c("","A", "B"), V2 = c("x",0,1), V3 = c("y",2,3), V4 = c("z",4,5))

DF2 = data.frame(V1 = c("","A", "B"), V2 = c("x",6,7), V3 = c("y",8,9), V4 = c("z",0,0))

so

> DF1                > DF2
   V1 V2 V3 V4          V1 V2 V3 V4
1     x  y  z        1     x  y  z
2  A  0  2  4        2  A  6  8  0
3  B  1  3  5        3  B  7  9  0

and I want to have the first row as column names here, so

>DF1                > DF2
    x y z               x y z
1 A 0 2 4           1 A 6 8 0
2 B 1 3 5           2 B 7 9 0

What I do to achieve this is

if("V2" %in% names(DF1)){
  names(DF1) = as.character(unlist(DF1[1,]))
  DF1 = DF1[-1, ]
}
if("V2" %in% names(DF2)){
  names(DF2) = as.character(unlist(DF2[1,]))
  DF2 = DF2[-1, ]
}

which does what we want in this example.

QUESTION: What's the best way here to avoid having two if statements here? The first thing that came to my mind is iterating over the two DFs in a loop, but this doesn't work because you have to rename the DFs (at least it didn't work for me)

Or more generally, how to avoid doing the same thing for multiple arguments where loops don't work

Aucun commentaire:

Enregistrer un commentaire