How can R loop over data frames?

后端 未结 2 1172
南旧
南旧 2020-12-05 12:03

Suppose there are many data frames that need the same operation performed on them. For example:

prefix <- c(\"Mrs.\",\"Mrs.\",\"Mr\",\"Dr.\",\"Mrs.\",\"M         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-05 12:42

    The single instance example would not really create an indicator in the usual sense since the non-"F" values would be and those would not work well within R functions. Both arithmetic operations and logical operations will return . Try this instead:

      df1$gender <- ifelse(prefix %in% c("Mrs.", "Ms") , "probably F",
                    ifelse( prefix=="Dr.", "possibly F",  # as is my wife.
                                           "probably not F"))
    

    Then follow @HongDoi's advice to use lists. And do not forget to a) return a full dataframe-object , and b) assign the result to an object name (both of which were illustrated but often forgotten by R-newbs.)

提交回复
热议问题