0

When I read the csv it adds a X to my first element. I don't know what's wrong?

Also when I add colnames to a dataframe my first row disappears.

> grocery<-read.csv("groceries.csv")
> grocery
       spinach X2.00
1         rice   3.0
2 toilet paper   4.0
3        bread   2.4
4         milk   3.1
5        apple   0.4
> 
> class(grocery)
[1] "data.frame"
> colnames(grocery)<-c("item","price")
> grocery
          item price
1         rice   3.0
2 toilet paper   4.0
3        bread   2.4
4         milk   3.1
5        apple   0.4
> 

Here's the raw csv:

spinach,2.00
rice,3.00
toilet paper,4.00
bread,2.40
milk,3.10
apple,0.40

2 Answers 2

3

try:

read.csv("groceries.csv", header=F)

by default that function assumes the first row of your data is a header, and uses it for colnames instead of as data. Since numbers are not valid colnames, it prepends X to the numbers to make it character. When you re-set colnames, you overwrite what used to be the first row of your data that was actually saved as colnames instead of as a row of data.

Setting header=F will prevent read.csv from using the first row as colnames.

Sign up to request clarification or add additional context in comments.

Comments

1

you're also losing your first row of data, spinach and 2.00. It's making those the column names, 2.00 becomes X2.00 to comply with R naming conventions of permissible names. Add column headers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.