仅转换(洗牌)Dataframe 中的 2 个字段

Transform (shuffle) just 2 Fields in a Dataframe

我有一个包含名字、姓氏的数据框,我想对它们进行排列,但仅限于具有值的行。有许多空字段,我不希望对它们重新排序,以便有一个没有姓氏值的名字值。例如:

number<- c(1,2,3,4,5)
firstname<- c('','Eddie','Edward','','Edurardo')
lastname <- c('','Vedder', 'Van Halen', '', 'Norton')
permtest <- data.frame(number,firstname,lastname)
permtest
  number firstname  lastname
1      1                    
2      2     Eddie    Vedder
3      3    Edward Van Halen
4      4                    
5      5  Eduardo    Norton

预期结果为:

但不是:

或:

我尝试了转换功能,但没有用:

permtest2 <- transform( permtest2, firstname = sample(firstname,lastname) )

有帮助的是仅洗牌非空条目:

permtest$lastname[permtest$lastname != ''] <- sample(permtest$lastname[permtest$lastname != ''])
permtest
#   number firstname  lastname
# 1      1                    
# 2      2     Eddie Van Halen
# 3      3    Edward    Vedder
# 4      4                    
# 5      5  Edurardo    Norton

执行此操作的多种方法之一:

permtest[permtest == ''] = NA

library(dplyr)

permtest %>% 
  dplyr::filter(!is.na(lastname), !is.na(firstname)) %>% 
  dplyr::mutate(val = paste(firstname, lastname)) %>% 
  dplyr::pull(val)

[1] "Eddie Vedder"     "Edward Van Halen" "Edurardo Norton" 

使用 tidyverse 你可以做到

library(tidyverse)
library(stringr)

permtest2 <- permtest %>% mutate(Nfname = str_length(firstname)) %>% filter(Nfname > 0) %>% mutate(lastname = sample(lastname, size = length(lastname))) %>% select(-Nfname)