在 data.frame 上应用 strsplit 会导致意外输出

问题描述 投票:0回答:2

我有一个数据框和两个函数:

我的数据框:

s_words<-c("one,uno","two,dos","three,tres","four,cuatro")
n_nums<-c(10,20,30,40)
df1 <- data.frame(n_nums,s_words) 
> df1
  n_nums     s_words
1     10     one,uno
2     20     two,dos
3     30  three,tres
4     40 four,cuatro

我的两个功能:

f_op1 <- function(s_input) {
  s_ret = paste0("***",s_input,"***")
  return(s_ret)
}


f_op2 <- function(s_input) {
    a_segments=unlist(strsplit(s_input,split="\\W+"))
    s_eng = a_segments[1]
    s_spa = a_segments[2]
    s_ret = paste0("*",s_eng,"***",s_spa,"*")
  return(s_ret)
}

当我在数据框上应用我的函数时......

df1$s_op1 <- f_op1(df1$s_words)
df1$s_op2 <- f_op2(df1$s_words)

我明白了:

> df1
  n_nums     s_words             s_op1       s_op2
1     10     one,uno     ***one,uno*** *one***uno*
2     20     two,dos     ***two,dos*** *one***uno*
3     30  three,tres  ***three,tres*** *one***uno*
4     40 four,cuatro ***four,cuatro*** *one***uno*

但是我需要这个,比如:

> df1
  n_nums     s_words             s_op1           s_op2
1     10     one,uno     ***one,uno***     *one***uno*
2     20     two,dos     ***two,dos***     *two***dos*
3     30  three,tres  ***three,tres***  *three***tres*
4     40 four,cuatro ***four,cuatro*** *four***cuatro*

f_op2 仅用于演示目的,实际上它更复杂并使用“strsplit”。 我认为 strsplit 有一些问题,但我不确定,我是 R 语言的初学者。 预先感谢您的解释。

我已经寻求了很多帮助,但找不到解决方案。

r dataframe
2个回答
1
投票

strsplit() 返回向量列表,因此我们可以使用 sapply() 从每个向量中提取相关部分:

f_op2 <- function(s_input) {
  a_segments = strsplit(s_input,split="\\W+")
  s_eng = sapply(a_segments, \(x) x[1])
  s_spa = sapply(a_segments, \(x) x[2])
  s_ret = paste0("*",s_eng,"***",s_spa,"*")
  return(s_ret)
}

0
投票

使用

sprintf
gsub

> fn <- \(x) data.frame(s_op1=sprintf('***%s***', x), 
+                       s_op2=sprintf('*%s*', gsub(',', '***', x)))
> cbind(df1, fn(df1$s_words))
  n_nums     s_words             s_op1           s_op2
1     10     one,uno     ***one,uno***     *one***uno*
2     20     two,dos     ***two,dos***     *two***dos*
3     30  three,tres  ***three,tres***  *three***tres*
4     40 four,cuatro ***four,cuatro*** *four***cuatro*

数据:

> dput(df1)
structure(list(n_nums = c(10, 20, 30, 40), s_words = c("one,uno", 
"two,dos", "three,tres", "four,cuatro")), class = "data.frame", row.names = c(NA, 
-4L))
© www.soinside.com 2019 - 2024. All rights reserved.