列值的切换功能 [英] switch function for column values

查看:19
本文介绍了列值的切换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个首字母变量,名称错误地分散在整个列表中.请参阅下面的示例结构:

I have a variable of initials, with names erroneously scattered throughout the list. See example structure below:

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 的首字母.我目前不成功的代码示例有望说明:

I want to create a new variable (ID2), that switches out any names with assigned initials. Otherwise, I want ID2 to contain the initials from ID. An example of my currently unsuccessful code will hopefully illustrate:

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 来解决这个问题,因为我对这个函数还是很陌生.

This question is similar to one I asked previously (R: ifelse on string), however with the added variation of populating the rest of the column with values of the previous column. Additionally, I'd like to solve this using switch since I'm still fairly new to that function.

推荐答案

只需将 switch 函数中的最后一行切换为使用 x 而不是 test$ID

Just switch that last line in the switch function to use x instead of 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" 

Edit re Vectorize (Frank):如果你发现自己sapply经常这样做,你可能会考虑

Edit re Vectorize (Frank): If you find yourself sapplying this often, you might consider

swfun2 <- Vectorize(swfun)
unname(swfun2(ID))
 [1] "SPW" "SM"  "DLS" "SJ"  "JS"  "CEJ" "TR"  "GVF" "MJC"
[10] "LH"  "SF" 

或下面评论中链接的替代方案.

or the alternative linked in the comments below.

这篇关于列值的切换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆