从数据帧列生成R字符串

时间:2019-04-12 16:56:38

标签: r data-analysis

假设我在R中有一个带有两列的数据框

Name,Number

sample Dataset
"PETER","15401",
"SAMMY","68475"

现在我想为每一行创建一个新列,其值为<1st Digit in the Reverse of Number><First 3 digits in name><2nd Digit in Reverse of the number.>

因此上述数据集的解决方案应为

for 1.
"1PET0"
for 2
"5SAM7"

我是R语言的新手,所以请告诉我该怎么做。

2 个答案:

答案 0 :(得分:0)

我们可以将pastesubstr一起使用

df1$newcol <- with(df1, paste0(substr(Number, nchar(Number), nchar(Number)),
            substr(Name, 1, 3), 
           substr(Number, nchar(Number)-1, nchar(Number)-1)))
df1$newcol
#[1] "1PET0" "5SAM7"

数据

df1 <- structure(list(Name = c("PETER", "SAMMY"), Number = c(15401L, 
 68475L)), class = "data.frame", row.names = c(NA, -2L))

答案 1 :(得分:0)

stringi包因其stri_reverse功能而派上用场:

dat <- read.table(header = TRUE, text = "Name,Number
PETER,15401
SAMMY,68475", sep = ",") 

dat$new <- paste0(substr(stringi::stri_reverse(dat$Number), 1, 1), 
                  substr(dat$Name, 1, 3), 
                  substr(stringi::stri_reverse(dat$Number), 2, 2))

dat
#>    Name Number   new
#> 1 PETER  15401 1PET0
#> 2 SAMMY  68475 5SAM7

使用dplyr

library(dplyr)    
read.table(header = TRUE, text = "Name,Number
PETER,15401
SAMMY,68475", sep = ",") %>% 
  mutate(new = paste0(substr(stringi::stri_reverse(Number), 1, 1), 
                      substr(Name, 1, 3), 
                      substr(stringi::stri_reverse(Number), 2, 2)))
#>    Name Number   new
#> 1 PETER  15401 1PET0
#> 2 SAMMY  68475 5SAM7