[英]Converting data frame element to string in R
I have a list of letter pairs in df1
. 我在df1
有一个字母对列表。 The current dimension of df1
is 1,5 : df1
的当前尺寸为1,5:
df1= AC,AD,AE,AF,AG
I want to add a second row to df1 containing the reversed elements of df1
(dim: 2,5), ie: 我要添加的第二行至DF1包含的反转元件df1
(暗:2,5),即:
df1= AC,AD,AE,AF,AG
CA,DA,EA,FA,GA
I want to access the first row one element at a time, convert each to string, and then reverse it. 我想一次访问第一行一个元素,将每个元素转换为字符串,然后将其反转。 I've tried as.character(df1[1])
and toString(df1[1])
but they both give me "1"
as the result. 我已经尝试过as.character(df1[1])
和toString(df1[1])
但是它们都给我"1"
。 Could someone explain the error and how I could rectify it? 有人可以解释该错误,我该如何纠正?
EDIT: The output for str[df1]
is : 编辑: str[df1]
的输出是:
'data.frame': 1 obs. of 5 variables:
$ V1 : Factor w/ 1 level "AC": 1
$ V2 : Factor w/ 1 level "AD": 1
$ V3 : Factor w/ 1 level "AE": 1
$ V4 : Factor w/ 1 level "AF": 1
$ V5 : Factor w/ 1 level "AG": 1
Here is one way to do it with regular expressions: 这是使用正则表达式实现的一种方法:
df1 <- read.csv(text = "AC,AD,AE,AF,AG", header = FALSE) # your data frame
tmp <- sapply(df1, as.character) # a character vector
matrix(c(tmp, sapply(df1, sub, pattern = "(.)(.)", replacement = "\\2\\1")),
2, byrow = TRUE)
The result: 结果:
[,1] [,2] [,3] [,4] [,5]
[1,] "AC" "AD" "AE" "AF" "AG"
[2,] "CA" "DA" "EA" "FA" "GA"
The result is a matrix. 结果是一个矩阵。 It can be converted into a data frame with as.data.frame
. 可以使用as.data.frame
将其转换为数据帧。
generally as.matrix is a good coercion method. 通常as.matrix是一种很好的强制方法。
df <- data.frame(matrix(c("AC","AD","AE","AF","AG"), nrow=1))
df
X1 X2 X3 X4 X5
1 AC AD AE AF AG
sapply(df, function(x) paste(rev(strsplit(as.matrix(x), "")[[1]]), collapse=""))
X1 X2 X3 X4 X5
"CA" "DA" "EA" "FA" "GA"
does it answer? 它回答了吗?
Not sure that is the easiest way to do that but here is one approach that works The first step is to create your data.frame
不确定这是最简单的方法,但这是一种data.frame
方法第一步是创建data.frame
dat <- Reduce(data.frame,
c("AC", "AD", "AE", "AF", "AG"))
names(dat) <- paste0("V", 1:ncol(dat))
str(dat)
## 'data.frame': 1 obs. of 5 variables:
## $ V1: Factor w/ 1 level "AC": 1
## $ V2: Factor w/ 1 level "AD": 1
## $ V3: Factor w/ 1 level "AE": 1
## $ V4: Factor w/ 1 level "AF": 1
## $ V5: Factor w/ 1 level "AG": 1
And in a final step, we will create a function to reverse vector of string and apply it to the data 在最后一步,我们将创建一个函数以反转字符串向量并将其应用于数据
str_rev <- function(string)
paste(rev(unlist(strsplit(string, ""))), collapse = "")
str_rev <- Vectorize(str_rev, USE.NAMES = FALSE)
rbind(dat,
t(apply(dat, 1, str_rev))
)
## V1 V2 V3 V4 V5
## 1 AC AD AE AF AG
## 2 CA DA EA FA GA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.