d= cbind("Data", c("2", "73"))> d [,1] [,2][1,] "Data" "2" [2,] "Data" "73"What I want is to get strings like [,1][1,] "Data 2"[2,] "Data" />
Вопрос:

In R: Joining vector elements by row, converting vector rows to strings

r

11301 просмотра

3 ответа

1467 Репутация автора

Is there a "by row" operation in R to convert each row in a vector like this to strings?

> d= cbind("Data", c("2", "73"))
> d
     [,1]   [,2]
[1,] "Data" "2" 
[2,] "Data" "73"

What I want is to get strings like

     [,1]
[1,] "Data 2"
[2,] "Data 73"

Is there an easy way to join items by row?

Автор: gakera Источник Размещён: 18.11.2010 10:11

Ответы (3)


23 плюса

85809 Репутация автора

Решение

Yes, there is. It is called "apply" ;-)

apply(d,1,paste,collapse=" ")
[1] "Data 2"  "Data 73"
# convert to matrix using as.matrix to get exactly your solution

See ?apply and ?paste

Автор: Joris Meys Размещён: 18.11.2010 10:13

4 плюса

145967 Репутация автора

After a quick glace at ?paste, it's clear that apply isn't needed for the example given. It would be handy if there are several columns though.

> paste(d[,1],d[,2])
[1] "Data 2"  "Data 73"
Автор: Joshua Ulrich Размещён: 18.11.2010 03:56

3 плюса

61 Репутация автора

A general way to do it without resorting to ?apply:

do.call(paste, as.data.frame(d))
[1] "Data 2"  "Data 73"

Where as.data.frame is used to avoid subscripts.

Edit:

do.call is a function which takes another function as first argument, and a list as second argument. It is often used to send lists of arguments to functions (in our case, the columns of d to paste()). We send d as a data.frame (a type of list) for this trick to work.

Автор: Beginning_Math Размещён: 16.03.2016 06:50
Вопросы из категории :
32x32