我有一个名字首字母的变量,名字被错误地分散在列表中。见下面的示例结构:
ID <- c('SPW', 'SM', 'DLS', 'SJ', 'joe.schmoe', 'CEJ', 'teddy.roos', 'GVF', 'MJC',
'LH', 'sally.fields') ## Full names shouldn't be there -- only initials.
test <- data.frame(ID)我想要创建一个新的变量(ID2),它用指定的首字母替换任何名称。否则,我希望ID2包含ID中的首字母。
swfun <- function(x) {
switch(x,
'joe.schmoe' = 'JS',
'teddy.roos' = 'TR',
'sally.fields' = 'SF',
as.character(test$ID)
)
} ## In other words, I've created a switch function to replace any names
## with requisite initials. I was 'hoping' that the last command
## [as.character(test$ID)] would populate the rest of ID2 with values
## from test$ID.
test$ID2 <- sapply(test$ID, swfun)而不是得到test$ID2 <- c('SPW', 'SM', 'DLS', 'SJ', 'JS', 'CEJ', 'TR', 'GVF', 'MJC', 'LH', 'SF'),
我要去找test$ID2 <- list(NULL, NULL, "TR", NULL, c("SPW", "SM", "DLS", "SJ", "joe.schmoe", "CEJ", "teddy.roos", "GVF", "MJC", "LH", "sally.fields"), "JS", NULL, "SF", NULL, NULL, NULL)
这个问题类似于我之前问过的一个问题(R: ifelse on string),但是增加了将列的其余部分填充到上一列的值的变化。此外,我想使用switch来解决这个问题,因为我对这个函数还很陌生。
发布于 2013-09-23 02:23:54
只需将开关函数中的最后一行切换为使用x而不是test$ID
swfun <- function(x) {
switch(x,
'joe.schmoe' = 'JS',
'teddy.roos' = 'TR',
'sally.fields' = 'SF',
as.character(x)
)
}结果
> unname(sapply(ID, swfun))
[1] "SPW" "SM" "DLS" "SJ" "JS" "CEJ" "TR" "GVF" "MJC"
[10] "LH" "SF" 编辑re Vectorize (弗兰克):,如果您发现自己经常这样做,您可能会考虑
swfun2 <- Vectorize(swfun)
unname(swfun2(ID))
[1] "SPW" "SM" "DLS" "SJ" "JS" "CEJ" "TR" "GVF" "MJC"
[10] "LH" "SF" 或者在下面的评论中链接到的替代方案。
https://stackoverflow.com/questions/18950809
复制相似问题