如何遍历列名并使用特定列中的给定值更新数据框

时间:2019-01-14 12:08:39

标签: r

给出了雇员的角色以及该角色的开始日期。名为“角色”的数据框包含该名称。开始日期应使用用户为该特定名称提供的值填充,其余列应使用“-”填充

roles <- data.frame(character(),character(),character(),character(), 
                      stringsAsFactors = FALSE)

roles[1, ] <- ifelse(names(roles) == a,sd, "-")
roles
newrow =  data.table(`Manager_start` = roles[1,4],
                     `VP_start` = roles[1,3],
                     `AP_start` = roles[1,2],
                     `P_start` = roles[1,1])
          dbWriteTable(conn = con,"table_name",newrow,append=TRUE,row.names=FALSE)

预期结果是“管理器”列应具有值“ 12/12/12”,其他列应具有“-”。但是随机值会存储在数据库中,显示为“ 17914”

1 个答案:

答案 0 :(得分:1)

我们将继续您的尝试

roles <- data.frame(character(),character(),character(),character(), 
                          stringsAsFactors = FALSE)

roles[1, ] <- ifelse(names(roles) == a,sd, "-")
roles

#  VP Principal AP  Manager
#1  -         -  - 12/12/12

或其他选择

vec <- c("VP","Principal","AP","Manager")
setNames(data.frame(t(ifelse(vec == a, sd, "-"))), vec)

编辑

对于更新后的示例,此方法有效

a <- "Manager"
sd <- "12/12/12"
roles <- data.frame(character(),character(),character(),character(), 
                      stringsAsFactors = FALSE)
names(roles) <- c("VP","Principal","AP","Manager")

roles[1, ] <- ifelse(names(roles) == a,sd, "-")
newrow =  data.table(`Manager_start` = roles[1,4],
                     `VP_start` = roles[1,3],
                     `AP_start` = roles[1,2],
                     `P_start` = roles[1,1])

newrow
#   Manager_start VP_start AP_start P_start
#1:      12/12/12        -        -       -