R - 字符串处理的变异 - 没有得到我希望的行为

标签 r string dplyr

我正在尝试在 dplyr 中使用 mutate 来处理字符串,但我没有得到我想要的输出(见下文),mutate 不是逐行操作,而是获取第一个元素并将其向下填充。我想知道是否有人可以帮助我了解我做错了什么以及如何调整此代码以使其正常工作。

short.idfun = function(longid) 
{
    x      = strsplit(longid,"_")
    y      = x[[1]]
    study  = substr(y[1],8,nchar(y[1]))
    subj   = y[length(y)]
    subj   = substr(subj,regexpr("[^0]",subj),nchar(subj)) #remove leading zeros
    shortid= paste(study,subj,sep="-")
    return(shortid)
}

data = data.frame(test=c("1234567Andy_003_003003","1234567Beth_004_003004","1234567Char_003_003005"),stringsAsFactors=FALSE)
data= mutate(data,shortid=short.idfun(test))
print(data)

#### Below is my output
#                       test   shortid
#1    1234567Andy_003_003003 Andy-3003
#2    1234567Beth_004_003004 Andy-3003
#3    1234567Char_003_003005 Andy-3003

#### This is the behavior I was hoping for
#                       test   shortid
#1    1234567Andy_003_003003 Andy-3003
#2    1234567Beth_004_003004 Beth-3004
#3    1234567Char_003_003005 Char-3005

最佳答案

另一种选择是使用 rowwise():

data %>%
  rowwise() %>% 
  mutate(shortid = short.idfun(test))

给出:

#Source: local data frame [3 x 2]
#Groups: <by row>
#
#                    test   shortid
#                   (chr)     (chr)
#1 1234567Andy_003_003003 Andy-3003
#2 1234567Beth_004_003004 Beth-3004
#3 1234567Char_003_003005 Char-3005

关于R - 字符串处理的变异 - 没有得到我希望的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643632/

相关文章:

r - 在ggplot中为多个组绘制配对数据

r - 在 R 中,如何制作一个六条形图,其中每个条形包含一系列数据?

r - 使用 `st_intersection(x)` 后如何获取所有相交多边形的属性?

java - 字符串 "--"是不允许的,java 项目

php - 如何在不在 PHP 中循环的情况下创建具有 x 个相同字符的字符串

javascript - 在 javascript 中获得映射和过滤器的好处的最优雅的方法是减少数组并更改其中的变量

R {dplyr} : `rename` or `mutate` data. 帧在 LHS 上具有不同列名的 `rowwise` 列表列

r - NSE lazyeval::lazy 与引用变量名时的替换

r - dplyr | group_by 与 anti_join |最有效的方法

r - 如果对象是从文件中新加载的,data.table 不会通过引用修改?