mercredi 27 mars 2019

How to make the code in my function return editted dataframes

I am attempting to use ifelse statements in R to add a specific prefix to my dataframes.

I have two issues with my code at the moment.

1) When I try to wrap this in a function it does not return the edited dataframes.

2) the no = parameter of the ifelse statement I have put in repeats itself, how do I make this only repeat once?

Would appreciate any help.

note. I am using some made up data in this example, due to professional reasons.


dput(head(Player1)):

structure(list(Class = structure(c(2L, 1L, 5L, 4L, 3L), .Label = c("fighter", 
"paladin", "rouge", "sorceror", "wizard"), class = "factor"), 
Race = structure(c(3L, 1L, 4L, 3L, 2L), .Label = c("elf", 
"gnome", "human", "orc"), class = "factor"), alignment = structure(c(4L, 
2L, 1L, 5L, 3L), .Label = c("CE", "CG", "LG", "NE", "NN"), class = "factor"), 
Level = c(6, 7, 1, 2, 4)), row.names = c(NA, 5L), class = "data.frame")

dput(head(Player2)):

structure(list(Class = structure(c(2L, 1L, 5L, 4L, 3L), .Label = c("fighter", 
"paladin", "rouge", "sorceror", "wizard"), class = "factor"), 
Race = structure(c(3L, 1L, 4L, 3L, 2L), .Label = c("elf", 
"gnome", "human", "orc"), class = "factor"), alignment = structure(c(4L, 
2L, 1L, 5L, 3L), .Label = c("CE", "CG", "LG", "NE", "NN"), class = "factor"), 
Level = c(6, 7, 1, 2, 4)), row.names = c(NA, 5L), class = "data.frame")


Let's say we have two players John (player1) and Lucy (player2) and we want to add a prefix's on their colnames. I have achieved this by using the code below.

ifelse(test = grepl('Johns', names(Player1)) == F, 
         yes = colnames(Player1) <- paste('Johns', colnames(Player1), sep = '_'),
         no = print('Player info is fine'))

The output here works and all columns get 'Johns_' as a prefix However, when I attempt to wrap this into a function for both players the data frames there is no change.

Function:

Addnames <- function(Player1, Player2){
  ifelse(test = grepl('Johns', names(Player1)) == F, 
         yes = colnames(Player1) <- paste('Johns', colnames(Player1), sep = '_'),
         no = print('Player info is fine'))
  ifelse(test = grepl('Lucys', names(Player2)) == F, 
         yes = colnames(Player2) <- paste('Lucys', colnames(Player2), sep = '_'),
         no = print('Player info is fine'))
return(Player1)
return(Player2)
}

Addnames(Player1, Player2) 

This does not edit the colnames of the data frames.


My ideal output is to have 'Johns_' and 'Lucys_' as a prefix on each column name for Player1 and Player2 data frames, respectively.

I would to do this in a function.

Another issue I have is inside the ifelse statement if no = 'Player info is fine' repeats itself for each column name. How do I get this to only repeat itself once.

Again any help would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire