Reputation: 57176
I have this data for instance,
>rows
ID NAME AGE ADDRESS SALARY
1 1 Paul 32 California 20000
2 2 Allen 25 Texas 15000
3 3 Teddy 23 Norway 20000
4 4 Mark 25 Rich-Mond 65000
5 5 David 27 Texas 85000
6 6 Kim 22 South-Hall 45000
and to get the data in the name columns only,
> rows[2]
NAME
1 Paul
2 Allen
3 Teddy
4 Mark
5 David
6 Kim
And I want to join them into a string,
> paste(rows[2],collapse=" ")
result,
[1] c("Paul", "Allen", "Teddy", "Mark", "David", "Kim")
But this is what I am after,
Paul Allen Teddy Mark David Kim
Is it possible?
The entire code,
# Load package.
library("RSQLite")
# Load package.
library("sqldf")
# Load package.
library("tcltk")
# Connect to the sqlite file.
# Localhost.
DB <- dbConnect(SQLite(), dbname = "C:/../sqldf/testDB.sqlite3")
# Fetch all records in the table.
users <- dbGetQuery(
DB,
"SELECT *
FROM users"
)
# SQL statements can be run by using the sql methods provided by sqlContext
rows <- sqldf("SELECT * FROM users")
png(filename="temp.png", width=500, height=500)
plot(1, 1, col = "white")
text(1, 1, paste(rows[2], collapse = ' '))
dev.off()
Upvotes: 3
Views: 97
Reputation: 886938
We can use either
paste(rows[,2], collapse=' ')
Or
paste(rows[[2]], collapse=' ')
Or as @Frank mentioned, we can extract by the name of the column using either $
paste(rows$NAME, collapse=' ')
Or [[
paste(rows[['NAME']], collapse=' ')
as all of the above are extracting the columns as vector
while rows[2]
is still a data.frame. We can check the difference using str
i.e. str(rows[2])
and str(rows[[2]])
. For more info, we can look at ?Extract
or ?'['
Upvotes: 5