如何将这些系列命令转换为函数?

时间:2017-03-24 15:16:15

标签: r function for-loop

嗨我对R很新,并尝试自学,我想将以下代码集转换为for循环/函数,但我正在努力如何实现这一点,因为没有一套统一的可能条目。

以下是非功能形式的代码:

    colnames(x)[36] <- "DriveToFoodSource_BIN"
    x[,36][x[,36] == "Drive"] <- "1"
    x[,36][x[,36] == ""] <- "0"

    colnames(x)[37] <- "BusToFoodSource_BIN"
    x[,37][x[,37] == "Ride the bus"] <- "1"
    x[,37][x[,37] == ""] <- "0"

    colnames(x)[38] <- "TaxiToFoodSource_BIN"
    x[,38][x[,38] == "Taxi cab"] <- "1"
    x[,38][x[,38] == ""] <- "0"

    colnames(x)[39] <- "FriendsBringFoodSource_BIN"
    x[,39][x[,39] == "Friend"] <- "1"
    x[,39][x[,39] == ""] <- "0"

    colnames(x)[40] <- "WalkToFoodSource_BIN"
    x[,40][x[,40] == "Walk"] <- "1"
    x[,40][x[,40] == ""] <- "0"

    colnames(x)[41] <- "DeliveryFoodSource_BIN"
    x[,41][x[,41] == "Food is delivered"] <- "1"
    x[,41][x[,41] == ""] <- "0"

    colnames(x)[42] <- "OtherWayToFoodSource_BIN"
    x[,42][x[,42] == "Drive"] <- "1"
    x[,42][x[,42] == ""] <- "0"

1 个答案:

答案 0 :(得分:1)

我们可以分两步完成这项工作

1)通过将列与复制的vector值进行比较,将列更改为二进制,然后将logical强制转换为binary并将这些值分配给感兴趣的专栏

x[36:42] <- +(x[36:42]== v1[col(x[36:42])])

2)更改这些列的列名称

colnames(x)[36:42] <- v2

数据

v1 <- c("Drive", "Ride the bus", "Taxi cab", "Friend", "Walk", "Food is delivered",
    "Drive")
v2 <- c("DriveToFoodSource_BIN", "BusToFoodSource_BIN", "TaxiToFoodSource_BIN", 
   "FriendsBringFoodSource_BIN", "WalkToFoodSource_BIN","DeliveryFoodSource_BIN",
           "OtherWayToFoodSource_BIN")