0

I am reading in data from a .txt file that contains over thousands of records

table1 <- read.table("teamwork.txt", sep ="|", fill = TRUE)

Looks like:

f_name  l_name hours_worked  code

Jim      Baker    8.5        T
Richard  Copton  4.5         M
Tina     Bar     10          S

However I only want to read in data that has a 'S' or 'M' code:

I tried to concat the columns:

newdata <- subset(table1, code = 'S' |'M')

However I get this issue:

operations are possible only for numeric, logical or complex types

royalblue
  • 439
  • 2
  • 8
  • 18

2 Answers2

1

If there are thousands or tens of thousands of records (maybe not for millions), you should just be able to filter after you read in all the data:

> library(tidyverse)
> df %>% filter(code=="S"|code=="M")
# A tibble: 2 x 4
  f_name  l_name hours_worked code 
  <fct>   <fct>         <dbl> <fct>
1 Richard Copton         4.50 M    
2 Tina    Bar           10.0  S    

If you really want to just pull in the rows that meet your condition, try sqldf package as in example here: How do i read only lines that fulfil a condition from a csv into R?

mysteRious
  • 4,102
  • 2
  • 16
  • 36
  • It is giving me `Error in filter_impl(.data, quo) : Evaluation error: object 'code' not found.` error any idea on it please? – RavinderSingh13 Jun 25 '18 at 17:10
  • I loaded in your data that you included in the question as a data frame called `df` with four variables: `f_name`, `l_name`, `hours_worked`, and `code`. If your data frame name is different, just replace `df` in the above code; similarly, if your variable name is different than `code`, you will have to use your variable name. – mysteRious Jun 25 '18 at 17:52
0

You can try

cols_g <- table1[which(table1$code == "S" | table1$code == "M",]

OR

cols_g <- subset(table1, code=="S" | code=="M")

OR

library(dplyr)
cols_g <- table1 %>% filter(code=="S" | code=="M")

If you want to add column cols_g on table1, you can use table1$cols_g assigned anything from these 3 methods instead of cols_g.

juzraai
  • 5,693
  • 8
  • 33
  • 47