Greg
Greg

Reputation: 47124

Get a value from a data frame and add it to a new data frame

In the code below I want to add the value 3431933 from the first row, sixth column in my_data to the new_data object.

Instead it seems to be adding the number 2. Could you guys help me locate where I'm going wrong, or what my fundamental misunderstanding might be?

My Code:

print(my_data);
new_data <- {};
my_row <- my_data[1,];
print(my_row[1,6]);
new_data <- rbind(new_data, c(my_row[1,6]));
print(new_data);

Here's what I'm seeing in the printed output:

What's in my_data:

     V1            V2 V3   V4   V5       V6       V7            V8
1 10705 indiv7_ACTGAC  2  270  271  3431933  3442637          <NA>
2 41094 indiv7_ACTGAC  2  886  891 10296043 10337136 10297027.1114
3 18841 indiv7_ACTGAC  2 3497 3498 41414296 41433136          <NA>
                V9
1             <NA>
2 10335630.1686849
3             <NA>

What prints out for my_row[1,6]:

[1] 3431933
Levels: 10296043 3431933 41414296

What prints out for new_data:

         [,1]

[1,]    2

Upvotes: 1

Views: 54

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

you have a factor (ie, a categorical variable), which you need to convert to a number or character

#instead of: 
my_row[1,6]

# use: 
as.numeric(as.character(my_row[1,6]))

What gives away the fact that you are dealing with factors is that when you print it out, it is followed by Levels: .... (You can also check by calling is.factor()).

The number 2 that you are getting represents the second level of your variable.

Upvotes: 1

Related Questions