1

I have a .txt data file and I want to perform a very simple operation, namely creating a vector/column with values that are created by dividing a column of the .txt by another column of the .txt.

It seems very trivial but I haven't found out how to do this. First I encountered problems with the type of entries. Being non-numeric I created a for-loop making them all numeric but even after that I didn't succeed. Therefore I now ask the question from stratch.

My text file looks like this:

state drivers cars pop
AK 360 5.1 5877 
AL 498 34.4 3942 
AR 219 19.2 3585 
AZ 728 31.3 7116 
CA 6539 336.2 6518 

Now I just want to make a column (does not have to be included in the already existing table, can be just a new variable) with the values of column 2 divided by the values of column 3 divided by 10.

So far I just read the table as:

crimedata <- read.table("drivers.txt",stringsAsFactors=FALSE)

How to do this simple operation?

mck
  • 40,932
  • 13
  • 35
  • 50
Mathbeginner
  • 201
  • 1
  • 8

1 Answers1

0

We can do

crimedata$newcol <- with(crimedata, drivers/cars * 10)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I assume we change df1 into crimedata? I then get the error: `drivers not found` – Mathbeginner Apr 17 '19 at 10:01
  • @Mathbeginner Based on the data showed, 'drivers' is one of the column names, right? Can you check `str(crimedata)` – akrun Apr 17 '19 at 10:04
  • I guess it is a value in the table itself. For example `crimetable[1,2]` returns `drivers` – Mathbeginner Apr 17 '19 at 10:05
  • @Mathbeginner Can you check `colnames(crimetable)` – akrun Apr 17 '19 at 10:06
  • it returns `V1, V2 ,..`. I think I found what I did wrong! When I add `headers=T` in the read.table(), it does give headers! – Mathbeginner Apr 17 '19 at 10:07
  • @Mathbeginner You need to do `read.table("drivers.txt",stringsAsFactors=FALSE, header = TRUE)` while reading . Otherwise, it will think that the column names are the first row – akrun Apr 17 '19 at 10:07
  • Thank you so much. This was exactly what was wrong. Took me way too long to figure this out. Your help is much appreciated! – Mathbeginner Apr 17 '19 at 10:09