【问题标题】:How to loop through the column names and update the data frame with the given value in the particular column如何遍历列名并使用特定列中的给定值更新数据框
【发布时间】:2019-01-14 12:08:39
【问题描述】:

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

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)

预期结果是 Manager 列的值应为“12/12/12”,而其他列的值应为“-”。但是随机值会存储在数据库中,例如“17914”

【问题讨论】:

  • stringsAsFactors = FALSE 添加到您的data.frame 通话中,然后执行roles[1, ] &lt;- ifelse(names(roles) == a,sd, "-")
  • 它运作良好.. 谢谢
  • 使用 if(roles[i] == a) 代替 if(roles[i] = a) ?我无法编辑它,因为它少于 6 个字符。

标签: r


【解决方案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        -        -       -

【讨论】:

  • 但是一些垃圾值被存储在数据库中。对于 Manager 列,存储在后端的值为“17914”
  • @NevedhaAyyanar 这可能是因为您分配的值 (sd) 可能是因素。使用as.character(sd)将其转换为字符并检查结果。
  • @NevedhaAyyanar 那时不确定。您想更新您的示例,以便我们可以重现该问题,因为到目前为止它适用于您提供的示例数据?
  • 你现在能重现这个问题吗? @Ronak
  • 实际上不清楚你在这里做什么?为什么你在这里使用两个对象?你为什么使用 rolesnew_row ?一个是数据框,另一个是 data.table。
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 2021-03-08
  • 2020-01-02
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多