1

I have a problem regarding data conversion using R language.

I have two data that being stored in variables named lung.X and lung.y, below are the description of my data.

> str(lung.X)
 chr [1:86, 1:7129] "  170.0" "  104.0" "   53.7" "  119.0" "  105.5" "  130.0" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:86] "V3" "V4" "V5" "V6" ...
  ..$ : chr [1:7129] "A28102_at" "AB000114_at" "AB000115_at" "AB000220_at" ...

and

> str(lung.y)
 num [1:86] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...

lung.X is a matrix (row: 86 col: 7129) and lung.y is an array of numbers (86 entries)

Do anyone know how to convert above data into the format below?

> str(lung.X)
     num [1:86, 1:7129] 170 104 53.7 119 105.5 130...

I thought I should do like this

lung.X <- as.numeric(lung.X)

but I got this instead

> str(lung.X)
 num [1:613094] 170 104 53.7 119 105.5 130...

The reason of doing this is because I need lung.X to be numerical only.

Thank you.

4
  • 2
    Try lung.X[] <- as.numeric(lung.X) or mode(lung.X) <- "numeric". Commented Mar 23, 2016 at 17:13
  • 2
    Just add the dimensions attribute back, e.g. dim(lung.X) <- c(86,7129) Commented Mar 23, 2016 at 17:14
  • @sgibb, the first one does not function but the second one is working! Thank you. Commented Mar 23, 2016 at 17:40
  • @joran, yours is also working! Thank you. Commented Mar 23, 2016 at 17:42

2 Answers 2

1

Give this a try: m <- matrix(as.numeric(lung.X), nrow = 86, ncol = 7129)

If you need it in dataframe/list format, df <- data.frame(m)

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

1 Comment

No problem, Rafidah.
1

You could change the mode of your matrix to numeric:

## example data
m <- matrix(as.character(1:10), nrow=2,
            dimnames = list(c("R1", "R2"), LETTERS[1:5]))
m
#    A   B   C   D   E
# R1 "1" "3" "5" "7" "9"
# R2 "2" "4" "6" "8" "10"

str(m)
#  num [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:2] "R1" "R2"
#   ..$ : chr [1:5] "A" "B" "C" "D" ...
# NULL

mode(m) <- "numeric"
str(m)
#  num [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:2] "R1" "R2"
#   ..$ : chr [1:5] "A" "B" "C" "D" ...
# NULL
m
#    A B C D  E
# R1 1 3 5 7  9
# R2 2 4 6 8 10

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.