I have this csv file:
a,b,c,d,e
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
I name it data.csv
. Then I write the following script.
data <- read.csv('data.csv')
row <- data[2,]
row
dput(head(row))
barplot(row)
The output is the following:
$ Rscript testing.R
a b c d e
2 2 6 10 14 18
Error in barplot.default(row) : 'height' must be a vector or a matrix
Calls: barplot -> barplot.default
Execution halted
This doesn't happen with columns, i.e., if I use row <- data[,2]
. I get the following with this:
$ Rscript testing.R
[1] 5 6 7 8
How do I plot all the numbers in a row like I do for columns?
CodePudding user response:
When extracting a column of a data frame, we automatically get a verctor.
is.vector(dat[, 2])
# [1] TRUE
When we extract the row of a data frame, we still have a "data.frame"
which we want to unlist
in order to get the desired vector.
is.vector(dat[2, ])
# [1] FALSE
is.vector(unlist(dat[2, ]))
# [1] TRUE
Therefore you need to do this:
barplot(unlist(dat[2, ]))
Data:
data <- read.csv(text='a,b,c,d,e
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
')