0
$\begingroup$

I can't figure out how to add a constant value to a list. The list to which the data variable is bound was imported from a CSV file with 2 columns.

For example,

data = {{0.01, 0.02}, {0.08, 0.09}, {0.02, -0.05}, {0.03, 0.1}, ...}

How would I add a scalar value (e.g., +0.01) to the 2nd element of each pair?

The transformed data can be stored in a new variable data1.

$\endgroup$
2
$\begingroup$

you can try

#+{0,0.01}&/@{{0.01,0.02},{0.08,0.09},{0.02,-0.05},{0.03,0.1}}    

{{0.01, 0.03}, {0.08, 0.1}, {0.02, -0.04}, {0.03, 0.11}}

in other words

data1=#+{0,0.01}&/@data
| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Thank you. That's what I needed. $\endgroup$ – Robin Apr 20 '19 at 15:10
  • $\begingroup$ I'm glad I helped ! $\endgroup$ – J42161217 Apr 20 '19 at 15:11
3
$\begingroup$

Not the fastest, but simple to understand:

m = {{0.01,0.02},{0.08,0.09},{0.02,-0.05},{0.03,0.1}};
TranslationTransform[{0,.01}] @ m

{{0.01, 0.03}, {0.08, 0.1}, {0.02, -0.04}, {0.03, 0.11}}

Much faster is to use Transpose twice:

Transpose[Transpose[m] + {0., .01}]

{{0.01, 0.03}, {0.08, 0.1}, {0.02, -0.04}, {0.03, 0.11}}

Using Compile would be even faster.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Excellent approaches. I will definitely try this out for very large sets of data, which I have. $\endgroup$ – Robin Apr 20 '19 at 15:13
2
$\begingroup$

MapAt does exactly that:

data1 = MapAt[# + 0.01 &, data, {All, 2}]

| improve this answer | |
$\endgroup$
1
$\begingroup$

Here is an alternative way to do it. I am not sure if it is fast though.

data = {{0.01, 0.02}, {0.08, 0.09}, {0.02, -0.05}, {0.03, 0.1}};
data[[All, 2]] += 0.01;
data

{{0.01, 0.03}, {0.08, 0.1}, {0.02, -0.04}, {0.03, 0.11}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.