0

I have one vector created using the following code:

vectorA<-c(1.125,2.250,3.501) 

I have another vector stored in a data frame:

vectordf<-data.frame() vectordf[1,1]<-'1.125,2.250,3.501' vectorB<-vectordf[1,1] 

I need vectorB to be the same as vectorA so I can use it in another function. Right now the two vectors are different as shown below:

printerA<-paste("vectorA=",vectorA) printerB<-paste("vectorB=",vectorB) print(printerA) print(printerB) dput(vectorA) dput(vectorB) [1] "vectorA= 1.125" "vectorA= 2.25" "vectorA= 3.501" [1] "vectorB= 1.125 2.250 3.501" c(1.125, 2.25, 3.501) "1.125 2.250 3.501" 

How can I get vectorB into the same format as vectorA? I have tried using as.numeric, as.list, as.array, as.matrix.

1
  • vectorB <- scan(text = '1.125,2.250,3.501', sep = ",")? Commented Apr 20, 2021 at 14:16

2 Answers 2

1

This can be done with scan.

printerB<-paste("vectorB=", scan(text = vectordf[1,1], sep = ',')) 

And now printerA and printerB are

printerA #[1] "vectorA= 1.125" "vectorA= 2.25" "vectorA= 3.501" printerB #[1] "vectorB= 1.125" "vectorB= 2.25" "vectorB= 3.501" 
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that what you've called "vectorB" isn't quite a vector as you imagine it -- it's a string vector of length 1 consisting of numbers separated by commas.

Your idea to use as.numeric() is good, but as.numeric() doesn't quite know how to parse the string with commas as a vector of distinct numbers. So, you first want to split the string:

vectorB <- unlist(strsplit(vectorB, ",", fixed = T)) 

The strsplit() call will chop up vectorB into different vector sub-parts based on where it finds the commas. The data structure it returns is a list, so we flatten it back down to a vector with unlist(). Then, your as.numeric() idea will work:

vectorB <- as.numeric(vectorB) 

Obviously you can clean that up into a single line if you wish, but I wanted to clearly illustrate where the hole in your strategy was.


To make the answer more complete: the reason why this mismatch happened at all was in this line early on in your code:

vectordf[1,1]<-'1.125,2.250,3.501' 

The type of the object on the right side of <- is a string vector, and it's a vector of length 1. To fix this, you could have used

vectordf[1:3, 1] <- c(1.125, 2.25, 3.501) 

because the type of the object on the right is now a numeric vector of length 3. Note that we had to adjust the indexing on the left side by changing the row index to be 1:3.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.