Iterate over rows to split by " "
(strsplit
), sort and collapse back:
# Generate data
df <- data.frame(KEYWORD = c(paste(sample(letters, 3), collapse = " "),
paste(sample(letters, 3), collapse = " ")))
# KEYWORD
# z e s
# d a u
df$ALPHABETICAL <- apply(df, 1, function(x) paste(sort(unlist(strsplit(x, " "))),
collapse = " "))
# KEYWORD ALPHABETICAL
# z e s e s z
# d a u a d u
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…