4
$\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$

6 Answers 6

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
$\endgroup$
2
  • 1
    $\begingroup$ Thank you. That's what I needed. $\endgroup$
    – Robin
    Commented Apr 20, 2019 at 15:10
  • $\begingroup$ I'm glad I helped ! $\endgroup$
    – ZaMoC
    Commented Apr 20, 2019 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.

$\endgroup$
1
  • $\begingroup$ Excellent approaches. I will definitely try this out for very large sets of data, which I have. $\endgroup$
    – Robin
    Commented Apr 20, 2019 at 15:13
3
$\begingroup$

MapAt does exactly that:

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

$\endgroup$
2
$\begingroup$
data = {{0.01, 0.02}, {0.08, 0.09}, {0.02, -0.05}, {0.03, 0.1}};

Using Threaded (new in 13.1)

data1 = data + Threaded[{0, 0.01}]

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

$\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}}

$\endgroup$
1
$\begingroup$
data = {{0.01, 0.02}, {0.08, 0.09}, {0.02, -0.05}, {0.03, 0.1}};

Using SubsetMap:

SubsetMap[# + 0.01 &, data, {All, 2}]

(*{{0.01, 0.03}, {0.08, 0.1}, {0.02, -0.04}, {0.03, 0.11}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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