仅在1列中将数字更改为单词

时间:2015-05-08 18:37:33

标签: r

我想在我的数据集的1列中将0更改为Male,将1更改为Female。

Sex Age        LHUM RHUM    LRAD
0   40-50       0   1        0
1   50+         1   1        1
0   30-50       0   0        1
0   25-30       0   0        0
1   50+         0   0        0
1   30-40       0   0        0
0   30-50       0   0        0

3 个答案:

答案 0 :(得分:5)

试试这个:

//declare global variables

var full_map;
var locations_map;

function callIndex() {
    $(document).ready(function() {
 //call some functions
        load_map();
        load_test_map2();
        super_test_map();
        load_heat2(); 
    });

  $.ajax({
      url: 'php/get_map_tables.php',
      type: 'POST',
      dataType: 'JSON',
       data: {
          client_id: client_id, //defined elsewhere
      },
        success: function(data) { //this gives me the correct data in the right variables
            var locations_map = data[0].locations_map;
            var full_map = data[0].full_map;
        }
});
function load_heat2(){
       console.log(locations_map); //this yields undefined
}

} //end of callIndex function

答案 1 :(得分:2)

你可以尝试

 df1$Sex <- c('Male', 'Female')[df1$Sex +1L]
 df1$Sex
 #[1] "Male"   "Female" "Male"   "Male"   "Female" "Female" "Male"  

或者

df1$Sex <-  as.vector(factor(df1$Sex, labels=c('Male', 'Female')))

如果值为0和-1

 df1$Sex <- c('Male', 'Female')[ (-1*(df1$Sex))+1L]

数据

 df1 <- structure(list(Sex = c(0L, 1L, 0L, 0L, 1L, 1L, 0L), 
 Age =  c("40-50", 
"50+", "30-50", "25-30", "50+", "30-40", "30-50"), LHUM = c(0L, 
1L, 0L, 0L, 0L, 0L, 0L), RHUM = c(1L, 1L, 0L, 0L, 0L, 0L, 0L), 
LRAD = c(0L, 1L, 1L, 0L, 0L, 0L, 0L)), .Names = c("Sex", 
"Age", "LHUM", "RHUM", "LRAD"), class = "data.frame",
row.names = c(NA, -7L))

答案 2 :(得分:1)

plyr包具有用于进行此类替换的函数mapvalues

library(plyr)
df1$Sex <- mapvalues(df1$Sex, from = c(0,1), to = c("Male", "Female"))